Operations 14 min read

Shell Basics: Introduction, Commands, Variables, and Scripting

This article provides a comprehensive introduction to the Bash shell, covering its purpose, user prompts, shebang syntax, execution methods, basic commands like echo and printf, variable handling, environment variables, arithmetic operations, and conditional statements for writing effective shell scripts.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Shell Basics: Introduction, Commands, Variables, and Scripting

Shell Overview

The series of blogs uses Bash, the default shell on most GNU/Linux systems, so examples assume a Bash environment.

User Types

$   # ordinary user
#   # root (administrator)

Shebang

Shell scripts usually start with a shebang line, e.g., #!/bin/bash .

In Unix slang, "#" is called "sharp" or "hash" and "!" is called "bang".

/bin/bash indicates the path to the Bash interpreter; other interpreters can be used.

The kernel reads the first line, notices #!/bin/bash , and runs /bin/bash to execute the script.

Execution Methods

Run the script as a Bash argument:

bash script.sh

Give the script execute permission and run it as an executable file.

Relative path:

chmod a+x script.sh
./script.sh

Absolute path:

chmod a+x script.sh
/home/path/script.sh

Terminal Output Commands

echo Command

Usage rules:

By default, echo adds a newline after each call.
When using echo without quotes, a semicolon cannot appear in the text because it is a command delimiter.
With double quotes, special characters must be escaped with a backslash; single quotes do not require escaping.
Variable substitution does not work inside single quotes (e.g., ${username}).

Escape Characters

\a  alert (bell)
\b  delete previous character
\c  suppress trailing newline
\f  form feed (newline, cursor stays)
\n  newline, cursor moves to start of line
\r  carriage return (cursor to start, no newline)
\t  horizontal tab
\v  vertical tab (same as \f)
\\  backslash character
\nnn  octal ASCII character

Common Options

-n  omit the trailing newline
-e  enable interpretation of backslash escapes

Colored Output

Text Effects

0  reset all attributes
1  bold / high intensity
2  faint
3  italic
4  underline
5  blink
7  reverse video
8  conceal

Text Colors

reset=0, black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37

Background Colors

reset=0, black=40, red=41, green=42, yellow=43, blue=44, magenta=45, cyan=46, white=47

Examples

[root@localhost] $ echo -e "\e[1;31mWord is red \e[0m"
Word is red

[root@localhost] $ echo -e "\e[1;42mthe background is green \e[0m"
the background is green

[root@localhost] $ echo -e "\e[1;42;31mWord is red, the background is green \e[0m"
Word is red, the background is green

[root@localhost] $ echo -e "\e[5;37;31mMySQL Server Stop...\e[0m"
MySQL Server Stop...

[root@localhost] $ echo -e "\e[4;37;31mMySQL Server Stop...\e[0m"
MySQL Server Stop...

printf Command Usage

Unlike echo, printf does not automatically add a newline; you must include it explicitly.

Format Specifiers

%s  string
%c  character
%d  decimal integer
%f  floating‑point number

Alignment Formats

-   left‑align
(no flag) right‑align (default)
Width can be specified after the flag, e.g., %-10s
For floating point, precision can be set: %-4.2f

Examples

[root@localhost] $ printf "%-5s %-10s %-4.2f\n" 1 escape 100.123
1   escape   100.12

Variables and Environment Variables

Variables store data; in Bash every variable value is a string, regardless of quoting. Environment variables are used by the shell and the OS to store special values.

In Bash, each variable's value is a string.

Quotes do not affect the stored type; the value is always a string.

Environment variables are accessed by both the shell and the operating system.

Viewing Environment Variables

env               # list all terminal‑related variables
cat /proc/$PID/environ   # view variables for a specific process (null‑byte separated)
tr '\0' '\n'   # convert null separators to newlines

Using Variables

Define a variable:

var=value

Reference a variable:

echo $var
echo ${var}

Adding to the PATH Variable

# PATH is usually defined in /etc/environment, /etc/profile, or ~/.bashrc
export PATH="$PATH:/home/escape/bin"

Uses of Variables

Get string length: length=$(#var)

Identify the current shell: echo $SHELL or echo $0

Check for superuser: [ $UID -ne 0 ]

Modify the Bash prompt (PS1): PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$'

Add a directory to PATH via a function:

prepend() { [ -d "$2" ] && eval $1="$2:'$'$1" && export $1; }
# usage
prepend PATH /opt/myapp/bin

Performing Arithmetic Operations

Bash supports basic arithmetic with let , (( )) , or [] , and advanced calculations with expr and bc .

Basic Arithmetic

let
let result=num1+num2
let num++
let num--
let num+=5
let num-=5
result=$((num1+num2))
result=$(( $num+5 ))
result=$[ num1+num2 ]
result=$[ $num+5 ]

Advanced Arithmetic

expr
result=expr 3+4
result=$(expr $num+5)
bc
# simple multiplication
echo "4 * 0.56" | bc
# set scale (decimal precision)
echo "scale=2; 3/8" | bc
# decimal to binary
echo "obase=2; $num" | bc
# binary to decimal
echo "obase=10; ibase=2; $num" | bc
# square root
echo "sqrt(100)" | bc
# exponentiation
echo "10^10" | bc

Script Conditional Statements

Writing robust shell scripts requires familiarity with logical and file test operators.

Logical Tests

!   logical NOT
-a   logical AND
-o   logical OR

File Tests

[-e file]   # true if file exists
[-d file]   # true if file exists and is a directory
[-f file]   # true if file exists and is a regular file
[-b file]   # true if file exists and is a block special file
[-s file]   # true if file exists and size is non‑zero
[-c file]   # true if file exists and is a character special file
[-h file]   # true if file exists and is a symbolic link
[-p file]   # true if file exists and is a named pipe
[-r file]   # true if file is readable
[-w file]   # true if file is writable
[-x file]   # true if file is executable
[-L file]   # true if file is a symbolic link
[-S file]   # true if file is a socket
[-O file]   # true if file is owned by the effective user ID
[-G file]   # true if file is owned by the effective group ID
[-t FD]     # true if file descriptor FD is open and refers to a terminal
[-u file]   # true if set‑uid bit is set
[-g file]   # true if set‑gid bit is set
[-k file]   # true if sticky bit is set

Conditional Expressions

[string]          # true if string length is non‑zero
[-n string]       # true if string length is non‑zero
[-z string]       # true if string length is zero
[string1 == string2]  # true if strings are equal
[string1 != string2]  # true if strings are not equal
[string1 -eq string2]  # numeric equality
[string1 -ne string2]  # numeric inequality
[string1 -lt string2]  # less than
[string1 -gt string2]  # greater than
[string1 -le string2]  # less than or equal
[string1 -ge string2]  # greater than or equal
[file1 -nt file2]      # true if file1 is newer than file2
[file1 -ot file2]      # true if file1 is older than file2
[file1 -ef file2]      # true if file1 and file2 refer to the same inode
LinuxShellCommand-linescriptingbashvariablesprintf
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.