Shell Script Notes for Beginners

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

Steps:

  1. Install Vagrant and VirtualBox.
  2. Grab the CentOS 7 box script from here.
  3. Run the commands:
vagrant init centos/7
vagrant up
vagrant ssh
  1. Confirm you can SSH into CentOS (if prompted for credentials, use vagrant / vagrant).

Write and run a shell script

  1. Create a file:
touch hello.sh
  1. Edit it:
vi ./hello.sh
#!/bin/sh
echo "helloworld"
  1. Run it. Three options:
sudo chmod 755 ./hello.sh
./hello.sh

Basic operations (omitting #!/bin/sh)

echo text-to-print
read
expr 2 \+ 2
expr 2 \- 2
expr 2 \* 2
expr 2 \/ 2
a=1
b=2
r=`expr $a \+ $b`
echo $r
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.

var="red"
case "$var" in
  "blue" ) echo "blue" ;;
  "green" ) echo "green" ;;
  "red" ) echo "red" ;;
esac
int=0
while [ $int -lt 5 ]; do
  echo $int
  int=`expr $int \+ 1`
done
until [ ! \( $int -gt 0 \) ]; do
  echo $int
  int=`expr $int \- 1`
done
for var in 10 11 12 ; do
  echo $var
done
MyFunction () {
  echo "Function executed"
}
MyFunction
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!