-
Notifications
You must be signed in to change notification settings - Fork 0
Step 9: Linux shell scripting
monotiller edited this page Jun 8, 2022
·
1 revision
-
Bash scripts ususally have the extension
.sh
-
To run a bash script just use the command:
./script.sh
-
It is customary to start a script specifying what shell you want to run and where it is located:
For example:
#! /bin/bash
Basic bash script:
#! /bin/bash
# ECHO COMMAND
echo Hello World!
- Uppercase by convention
- Letters, numbers, underscores:
NAME="Florence"
echo "My name is ${NAME}"
read -p "Enter your name: " NAME
echo "Hello $NAME, nice to meet you!"
if [ "$NAME" == "Brad" ]
then
echo "Your name is Brad"
fi # Opposite of 'if' for the end of an if statement
if [ "$NAME" == "Brad" ]
then
echo "Your name is Brad"
else
echo "Your name is not Brad"
fi
if [ "$NAME" == "Brad" ]
then
echo "Your name is Brad"
elif [ "$NAME" == "Jack" ]
then
echo "Your name is Jack"
else
echo "Your name is not Brad or Jack"
fi
Returns true if:
-
-eq
equals -
-ne
not equals -
gt
greater than -
ge
greater than or equal to -
lt
less than -
le
less than or equal to
Returns true if:
-
-d file
the file is a directory -
-e file
the file exists -
-f file
is a file -
-g file
group id is set on a file -
-r file
file is readable -
-s file
file has a non-zero size -
-u
user id is set on a file -
-w
file is writeable -
-x
file is an executable
read -p "Are you 18 or over Y/N " ANSWER
case "$ANSWER" in
[yY] | [yY] [eE] [sS])
echo "You can have a beer :)"
;;
[nN] | [nN] [oO])
echo "Sorry, no drinking
;
*)
echo "Please enter y/yes or n/no"
esac
NAMES="Brad Kevin Alice Mark"
for NAME in $NAMES
do
echo "Hello $NAME"
done
FILES=$(ls *.txt)
NEW="new"
for FILE in $FILES
do
echo "Renaming $FILE to new-$FILE"
mv $FILE $NEW-$FILE
done
LINE=1
while read -r CURRENT_LINE
do
echo "$LINE: $CURRENT_LINE"
((LINE++))
done < "./new-1.txt"
function sayHello() {
echo "Hello World"
}
sayHello
function greet() {
echo "Hello, I am $1 and I am $2"
}
greet "Brad" "26"
mkdir hello
touch "hello/world.txt"
echo "Hello World" >> "hello/world.txt"
echo "Created hello/world.txt