사용자 도구

사이트 도구


linux:shell_script

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
linux:shell_script [2022/05/11 12:58]
kwon37xi
linux:shell_script [2024/01/19 08:09] (현재)
kwon37xi
줄 4: 줄 4:
   * [[linux:awk|awk]]   * [[linux:awk|awk]]
   * [[linux:xargs|xargs]]   * [[linux:xargs|xargs]]
 +
 +===== 인자 갯수 검사 Argument count =====
 +  * ''$#'' 가 스크립트의 인자 갯수를 가진 변수이다.
 +<code sh>
 +if [ "$#" -ne 2 ]; then
 +    echo "인자 2개를 넘겨주어야 합니다."
 +fi
 +</code>
  
 ===== pipe 출력 결과를 그대로 실행하기 ===== ===== pipe 출력 결과를 그대로 실행하기 =====
줄 47: 줄 55:
 </code> </code>
   * [[http://mywiki.wooledge.org/ProcessSubstitution|ProcessSubstitution - Greg's Wiki]]   * [[http://mywiki.wooledge.org/ProcessSubstitution|ProcessSubstitution - Greg's Wiki]]
 +
 +===== 실패시 fallback 처리 =====
 +  * ''명령 || 다른 명령'' 을 하면 첫번째 명령이 성공하면 그대로 넘어가고 실패했을 경우에는 다른 명령을 실행하고 그 결과를 최종 반환한다.
 +
 +<code sh>
 +# curl 명령 실패시에 "{}" 를 변수에 값으로 저장
 +TEST_RESULT=$(curl -Ss https://.... || echo "{}")
 +</code>
 +
 +===== 명령의 존재 검사 =====
 +  * ''command'' : POSIX 호환. 정확히는 명령에 대해 설명을 출력하는 것임. alias, function 등도 체크함.
 +
 +<code sh>
 +command -v <원하는명령>
 +
 +if ! command -v <the_command> &> /dev/null
 +then
 +    echo "<the_command> could not be found"
 +    exit
 +fi
 +</code>
 +  * ''hash <명령>'' : 일반적인 명령 검사. alias, function 도 존재여부 exit code로 확인가능. 명령이 존재하면 exit code ''0''이고 아니면 오류 메시지. 따라서 error stream 처리(''2>/dev/null'')이 필요하다.
 +  * ''type <명령>'' : shell 내장 명령 혹은 keyword 검사. 설명 메시지 혹은 존재하지 않는 명령이면 오류메시지. ''&>/dev/null'' stream 처리 필요.
 +<code sh>
 +if hash gdate 2>/dev/null; then
 +    gdate "$@"
 +else
 +    date "$@"
 +fi
 +</code>
 +  * [[https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script|How can I check if a program exists from a Bash script? - Stack Overflow]]
  
 ===== 참조 ===== ===== 참조 =====
linux/shell_script.1652241536.txt.gz · 마지막으로 수정됨: 2022/05/11 12:58 저자 kwon37xi