Shell - Basic Syntax

What is the shell?

A shell is a program that acts as the outermost layer of an operating system. It provides an interface for users to access the services of the kernel. It takes human-readable instructions and converts them into system calls that the kernel understands. The shell in macOS before Catalina is bash (Bourne Again Shell) and currently it’s Zsh (Z Shell). On most Linux distributions, the default shell is bash.

Basic shell commands

. # current directory
.. # parent directory
ls
mkdir
cd # change directory
pwd # print working directory
echo "text" # prints the specified text to the terminal
cat # displays the contents of the specified file
touch example.txt # creates a file
grep "Hello" example.txt # searches for the string “Hello” in a file named example.txt and returns the line containing it
export NODE_ENV=production # make a variable an environment variable

Basic Bash Syntax

Every shell script starts with a shebang line:

#!/bin/bash

This tells the system to run the script with Bash.

  • Define variables
name="Alice" # no space around "="
echo $name
echo "Hello, ${name}!"

In this example, name is variable name, $name represents getting the value of the variable.

  • Command substitution
% date
Fri Oct 24 01:19:10 PDT 2025
today=$(date) # $(date) runs the date command first, and replace it with its output
echo "Today is $today"

$() means running a command and store its output.

  • If statements
if [ $age -gt 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

Common operators: -eq, -ne, -gt, -ge, -lt, -le.

  • For loop
for var in item1 item2 item3; do
  echo "$var"
done
for f in *.txt; do # get all *.txt in the current directory
  echo "file: $f"
done
  • While loop
count=1
while [ $count -le 5 ]; do
  echo "Count $count"
  ((count++))
done
  • Arithmetic
    (( )) is used for arithmetic evaluation (like addition, subtraction, comparisons, and increments) in Bash.
((a = 5 + 3))
echo $a   # 8
((a++))
((c += 5))
((d *= 2))
a=5
b=3
if ((a > b)); then
  echo "a is greater"
fi

for ((i=1; i<=5; i++)); do
  echo "Number $i"
done
  • Functions
greet() {
    echo "Hello, $1"
}

greet "Alice"

$1 refers to the first argument passed to the function.

  • Special Functions
    ? and * can be used to match one or any amount of characters respectively.
% ls
01 hstack.py		04 mask.py		basic.ipynb
02 transpose.py		04 slicing.ipynb
03 least-square.py	05 histogram.py
% ls *.ipynb
04 slicing.ipynb	basic.ipynb
% ls b?sic.ipynb
basic.ipynb

{} can be used when a set of strings have common substrings.

% mkdir a b
% touch {a,b}/{x,y,z}
# The above command will create three files inside a and b folder (a/x, a/y, a/z, b/x, b/y, b/z) respectively.
mv *{.py,.ipynb} dest
# Will move all *.py and *.ipynb files to folder dest
  • Exit Status
    Every command in Linux returns an exit status. 0 means success, and non-zero means failure. $? is a special variable that stores the exit code of the most recent command.
ls /etc
echo $?   # 0 = success

ls /no/such/file
echo $?   # non-zero = error
if ls /no/such/file; then # if the ls command succeed, then print "Command succeeded"
  echo "Command succeeded"
else
  echo "Command failed"
fi

Tests

Tests are used in conditional statements.

  • -f file, File exists and is a regular file
if [ -f "config.txt" ]; then
  echo "Config file found"
else
  echo "No config file"
fi
  • -d file, file is a directory
  • -z "$str", string is empty
  • -n "$str", string is not empty
  • "$a" != "$b", strings are not equal

Find Files

find . -name src -type d
  • find .: Start searching in the current directory.
  • -name src: Match directories named src.
  • -type d: Ensure that the match is a directory.
find . -path '*/test/*.py' -type f
  • -path ‘/test/.py’: Match files where test appears as a directory in their path and the filename ends with .py (* can substitute any string).
  • -type f: Ensure that the match is a regular file (not a directory).

Special Parameters

  • $0, name of the current script
  • $1, first parameter
  • $#, number of parameters
  • $$, current script’s process ID
  • $?, exit status of the last command
  • $SHELL, current shell path
  • $PATH, directories to search for executables

Shell - Basic Syntax
http://example.com/2024/06/24/CS_Basis/Shell1/
Author
Songlin Zhao
Posted on
June 24, 2024
Licensed under