Scripting is one of the key tools for a sysadmin to manage a set of day-to-day activities such as running backups, adding users/groups, installing/updating packages, etc. While writing a script, error handling is one of the crucial things to manage.
This article shows some basic/intermediate techniques of dealing with error handling in Bash scripting. I discuss how to obtain the error codes, get verbose output while executing the script, deal with the debug function, and standard error redirection. Using these techniques, sysadmins can make their daily work easy.
[ Readers also liked: Bash command line exit codes demystified ]
Exit status
In Bash scripting, $? prints the exit status. If it returns zero, it means there is no error. If it is non-zero, then you can conclude the earlier task has some issue.
A basic example is as follows:
$ cat myscript.sh
#!/bin/bash
mkdir learning
echo $?
If you run the above script once, it will print 0 because the directory does not exist, therefore the script will create it. Naturally, you will get a non-zero value if you run the script a second time, as seen below:
$ sh myscript.sh
mkdir: cannot create directory 'learning': File exists
1
Best practices
It is always recommended to enable the debug mode by adding the -e option to your shell script as below:
$ cat test3.sh
!/bin/bash
set -x
echo "hello World"
mkdiir testing
./test3.sh
+ echo 'hello World'
hello World
+ mkdiir testing
./test3.sh: line 4: mkdiir: command not found
You can write a debug function as below, which helps to call it anytime, using the example below:
$ cat debug.sh
#!/bin/bash
_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}
DEBUG echo 'Testing Debudding'
DEBUG set -x
a=2
b=3
c=$(( $a + $b ))
DEBUG set +x
echo "$a + $b = $c"
Which prints:
$ ./debug.sh
Testing Debudding
+ a=2
+ b=3
+ c=5
+ DEBUG set +x
+ '[' on == on ']'
+ set +x
2 + 3 = 5
Standard error redirection
You can redirect all the system errors to a custom file using standard errors, which can be denoted by the number 2. Execute it in normal Bash commands, as demonstrated below:
$ mkdir users 2> errors.txt
$ cat errors.txt
mkdir: cannot create directory ‘users’: File exists
Most of the time, it is difficult to find the exact line number in scripts. To print the line number with the error, use the PS4 option (supported with Bash 4.1 or later). Example below:
$ cat test3.sh
#!/bin/bash
PS4='LINENO:'
set -x
echo "hello World"
mkdiir testing
You can easily see the line number while reading the errors:
$ /test3.sh
5: echo 'hello World'
hello World
6: mkdiir testing
./test3.sh: line 6: mkdiir: command not found
[ Get this free ebook: Managing your Kubernetes clusters for dummies. ]
Wrap up
Managing errors is a key skill for administrators when writing scripts. These tips should help make your life easier when troubleshooting Bash scripts or even general commands.
저자 소개
Ashutosh is an open source software advocate, docker community leader, Fedora active contributor, Red Hat / SUSE Certified Instructor with 19 years of experience as a trainer and consultant.
유사한 검색 결과
From manual to agentic: streamlining IT processes with Red Hat OpenShift AI
Automating Microsoft Endpoint Configuration Manager with Red Hat Ansible Automation Platform
Technically Speaking | Taming AI agents with observability
How Do We Make Updates Less Annoying? | Compiler
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
가상화
온프레미스와 클라우드 환경에서 워크로드를 유연하게 운영하기 위한 엔터프라이즈 가상화의 미래