It's an old quote, but I think this principle from Perl inventor Larry Wall is still valid:
"The lazy programmer will reuse whatever they can to get their work done. This virtue leads to code reuse by encouraging code to be written only once."
— Larry Wall, "The three virtues of a programmer"
Let's say you get tired of typing the same sequence of commands and finally create a nice shell script to run things with fewer keystrokes. But sometimes you want to run it with different arguments, and you definitely do not want to duplicate your great script. You need a way to provide and use arguments from the command line. This article covers exactly that.
Process script inputs
Shell scripts have access to some "magic" variables from the environment:
$0
- The name of the script$1
- The first argument sent to the script$2
- The second argument sent to the script$3
- The third argument... and so forth$#
- The number of arguments provided$@
- A list of all arguments provided
#!/bin/bash
if [ $# -eq 0 ];
then
echo "$0: Missing arguments"
exit 1
elif [ $# -gt 2 ];
then
echo "$0: Too many arguments: $@"
exit 1
else
echo "We got some argument(s)"
echo "==========================="
echo "Number of arguments.: $#"
echo "List of arguments...: $@"
echo "Arg #1..............: $1"
echo "Arg #2..............: $2"
echo "==========================="
fi
echo "And then we do something with $1 $2"
Here are a few examples of executing this with different combinations of arguments:
$ ./ex01.sh
./ex01.sh: Missing arguments
$ ./ex01.sh aa
We got some argument(s)
===========================
Number of arguments.: 1
List of arguments...: aa
Arg #1..............: aa
Arg #2..............:
===========================
And then we do something with aa
$ ./ex01.sh aa bb
We got some argument(s)
===========================
Number of arguments.: 2
List of arguments...: aa bb
Arg #1..............: aa
Arg #2..............: bb
===========================
And then we do something with aa bb
$ ./ex01.sh aa bb cc
./ex01.sh: Too many arguments: aa bb cc
This is fine if you have one or two arguments. However, notice the default separator between arguments is the Space character. And because Space is the default separator for arguments, interesting things can happen. For example, this is what happens if you use quotes with more than two arguments:
$ ./ex01.sh aa "bb cc xx yy zz"
We got some argument(s)
===========================
Number of arguments.: 2
List of arguments...: aa bb cc xx yy zz
Arg #1..............: aa
Arg #2..............: bb cc xx yy zz
===========================
And then we do something with aa bb cc xx yy zz
Notice that the script interprets bb cc xx yy zz
as one argument because the values are enclosed in double quotes, which is also fine if this is what you want.
[ Keep your Linux commands close at hand. Download the Advanced Linux commands cheat sheet. ]
Another interesting thing is when your script gets arguments from variables. If the variable contains spaces, you need to decide if you want that value to be treated as a single argument or all parts to be treated as different arguments:
$ export AUTHOR="John Lennon"
$ export SONG="Imagine"
$ ./ex01.sh $AUTHOR $SONG
./ex01.sh: Too many arguments: John Lennon Imagine
$ ./ex01.sh "$AUTHOR" "$SONG"
We got some argument(s)
===========================
Number of arguments.: 2
List of arguments...: John Lennon Imagine
Arg #1..............: John Lennon
Arg #2..............: Imagine
===========================
And then we do something with John Lennon Imagine
When you send the arguments as unquoted variables, the script interprets all of them as separate words and "sees" three arguments: John, Lennon, and Imagine.
Using quotes around the variables made the script receive each variable as one argument, which makes more sense in this case.
Handle many more arguments
As you saw, the magic variable $@
contains the list of all arguments received by the script. You can use a loop to process all the arguments:
#!/bin/bash
echo "We received $# argument(s)"
for i in "$@"
do
echo "Arg...: $i"
done
Which gives you this:
$ ./ex02.sh a b c e "stuff with spaces"
We received 5 argument(s)
Arg...: a
Arg...: b
Arg...: c
Arg...: e
Arg...: stuff with spaces
Be smart by being lazy
The important things when dealing with arguments in your shell scripts are to have a clear understanding of:
-
What form might the content of an argument take?
- If it is provided as a variable, what did the "sender" put in that variable for you?
- If it is provided by user input, how can you ensure the user doesn't "break" your logic?
- Which arguments are acceptable or mandatory for your script?
- What do you want to do if the arguments are invalid? The script could throw an error or perhaps use default values.
I hope this helps you continue being lazy in the right way... by improving or reusing some of your scripts.
저자 소개
Roberto Nozaki (RHCSA/RHCE/RHCA) is an Automation Principal Consultant at Red Hat Canada where he specializes in IT automation with Ansible. He has experience in the financial, retail, and telecommunications sectors, having performed different roles in his career, from programming in mainframe environments to delivering IBM/Tivoli and Netcool products as a pre-sales and post-sales consultant.
Roberto has been a computer and software programming enthusiast for over 35 years. He is currently interested in hacking what he considers to be the ultimate hardware and software: our bodies and our minds.
Roberto lives in Toronto, and when he is not studying and working with Linux and Ansible, he likes to meditate, play the electric guitar, and research neuroscience, altered states of consciousness, biohacking, and spirituality.
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
오리지널 쇼
엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리
제품
- Red Hat Enterprise Linux
- Red Hat OpenShift Enterprise
- Red Hat Ansible Automation Platform
- 클라우드 서비스
- 모든 제품 보기
툴
체험, 구매 & 영업
커뮤니케이션
Red Hat 소개
Red Hat은 Linux, 클라우드, 컨테이너, 쿠버네티스 등을 포함한 글로벌 엔터프라이즈 오픈소스 솔루션 공급업체입니다. Red Hat은 코어 데이터센터에서 네트워크 엣지에 이르기까지 다양한 플랫폼과 환경에서 기업의 업무 편의성을 높여 주는 강화된 기능의 솔루션을 제공합니다.