Shell Script Notes for Beginners
- #CLI
- #Shell Script
- #Tips
- #Know-how
- 2018/10/06
Getting started with shell scripts
I expect to write more shell soon, so I decided to learn the basics even as a beginner.
Build the environment
- CentOS 7
- Vagrant
- VirtualBox
Steps:
- Install Vagrant and VirtualBox.
- Grab the CentOS 7 box script from here.
- Run the commands:
vagrant init centos/7
vagrant up
vagrant ssh
- Confirm you can SSH into CentOS (if prompted for credentials, use
vagrant/vagrant).
Write and run a shell script
- Create a file:
touch hello.sh
- Edit it:
vi ./hello.sh
#!/bin/sh
echo "helloworld"
- Run it. Three options:
sh hello.shbash hello.sh- Make it executable:
sudo chmod 755 ./hello.sh
./hello.sh
Basic operations (omitting #!/bin/sh)
- Output:
echo text-to-print
- Read input:
read
- Arithmetic:
expr 2 \+ 2
expr 2 \- 2
expr 2 \* 2
expr 2 \/ 2
- Assign variables:
a=1
b=2
- Capture command results with backticks (note the spaces):
r=`expr $a \+ $b`
- Print variables:
echo $r
ifstatements:
if [ $res -eq $zero ]; then
echo "Even"
else
echo "Odd"
fi
# String comparison uses =
if [ "ABC" = "ABC" ]; then
echo "equal"
else
echo "not equal"
fi
-eq compares numbers.
case(switch):
var="red"
case "$var" in
"blue" ) echo "blue" ;;
"green" ) echo "green" ;;
"red" ) echo "red" ;;
esac
whileloop (-lt==<):
int=0
while [ $int -lt 5 ]; do
echo $int
int=`expr $int \+ 1`
done
untilloop (-gt==>):
until [ ! \( $int -gt 0 \) ]; do
echo $int
int=`expr $int \- 1`
done
forloop:
for var in 10 11 12 ; do
echo $var
done
- Function:
MyFunction () {
echo "Function executed"
}
MyFunction
- Function with arguments:
add () {
echo `expr $1 \+ $2`
}
add 1 3
Closing thoughts
Shell scripting is unavoidable, so I am studying it early in my career. I stumbled over missing spaces and the CRLF line endings that Windows editors insert—Linux expects LF, so watch out!
Share:
X (Twitter)