Shell
Work through every question currently mapped to this canonical topic.
- What does this line in shell scripts means?: #!/bin/bash
Answer
#!/bin/bashis She-bang/bin/bash is the most common shell used as default shell for user login of the linux system. The shellβs name is an acronym for Bourne-again shell. Bash can execute the vast majority of scripts and thus is widely used because it has more features, is well developed and better syntax.
- True or False? When a certain command/line fails in a shell script, the shell script, by default, will exit and stop running
Answer
Depends on the language and settings used. If the script is a bash script then this statement is true. When a script written in Bash fails to run a certain command it will keep running and will execute all other commands mentioned after the command which failed.
Most of the time we might actually want the opposite to happen. In order to make Bash exist when a specific command fails, use 'set -e' in your script.
- What do you tend to include in every script you write?
Answer
Few example:
- Comments on how to run it and/or what it does
- If a shell script, adding "set -e" since I want the script to exit if a certain command failed
You can have an entirely different answer. It's based only on your experience and preferences.
- Today we have tools and technologies like Ansible, Puppet, Chef, ... Why would someone still use shell scripting?
Answer
- Speed
- Flexibility
- The module we need doesn't exist (perhaps a weak point because most CM technologies allow to use what is known as "shell" module)
- We are delivering the scripts to customers who don't have access to the public network and don't necessarily have Ansible installed on their systems.
- Speed
- How to define a variable with the value "Hello World"?
Answer
HW="Hello World - How to define a variable with the value of the current date?
Answer
DATE=$(date) - How to print the first argument passed to a script?
Answer
echo $1 - Write a script to print "yay" unless an argument was passed and then print that argument
Answer
echo "${1:-yay}" - What would be the output of the following script?
#!/usr/bin/env bash NINJA_TURTLE=Donatello function the_best_ninja_turtle { local NINJA_TURTLE=Michelangelo echo $NINJA_TURTLE } NINJA_TURTLE=Raphael the_best_ninja_turtleAnswer
Michelangelo
- Explain what would be the result of each command:
- echo $0
- echo $?
- echo $$
- echo $#
π§ Answer not written yet.
- echo $0
- What is $@?
π§ Answer not written yet.
- What is difference between $@ and $*?
Answer
$@is an array of all the arguments passed to the script$*is a single string of all the arguments passed to the script - How do you get input from the user in shell scripts?
Answer
Using the keyword read so for example read x will wait for user input and will store it in the variable x.
- How to compare variables length?
Answer
if [ ${#1} -ne ${#2} ]; then ... - Explain conditionals and demonstrate how to use them
π§ Answer not written yet.
- In shell scripting, how to negate a conditional?
π§ Answer not written yet.
- In shell scripting, how to check if a given argument is a number?
Answer
regex='^[0-9]+$' if [[ ${var//*.} =~ $regex ]]; then ... - How to perform arithmetic operations on numbers?
Answer
One way:
$(( 1 + 2 ))Another way:expr 1 + 2 - How to perform arithmetic operations on numbers?
π§ Answer not written yet.
- How to check if a given number has 4 as a factor?
Answer
if [ $(($1 % 4)) -eq 0 ]; then - What is a loop? What types of loops are you familiar with?
π§ Answer not written yet.
- Demonstrate how to use loops
π§ Answer not written yet.
- How do you debug shell scripts?
Answer
Answer depends on the language you are using for writing your scripts. If Bash is used for example then:
- Adding -x to the script I'm running in Bash
- Old good way of adding echo statements
If Python, then using pdb is very useful.
- Running the following bash script, we don't get 2 as a result, why?
x = 2 echo $xAnswer
Should be
x=2 - How to extract everything after the last dot in a string?
Answer
${var//*.} - How to extract everything before the last dot in a string?
Answer
${var%.*}
- Generate 8 digit random number
Answer
shuf -i 9999999-99999999 -n 1
- Can you give an example to some Bash best practices?
π§ Answer not written yet.
- What is the ternary operator? How do you use it in bash?
Answer
A short way of using if/else. An example:
[[ $a = 1 ]] && b="yes, equal" || b="nope"
- What does the following code do and when would you use it?
diff
Answer
It is called 'process substitution'. It provides a way to pass the output of a command to another command when using a pipe | is not possible. It can be used when a command does not support STDIN or you need the output of multiple commands. https://superuser.com/a/1060002/167769
- What are you using for testing shell scripts?
Answer
bats
- Argument Check
Objectives
Note: assume the script is executed with an argument
- Write a script that will check if a given argument is the string "pizza"
- If it's the string "pizza" print "with pineapple?"
- If it's not the string "pizza" print "I want pizza!"
Answer
Objectives
Note: assume the script is executed with an argument
- Write a script that will check if a given argument is the string "pizza"
- If it's the string "pizza" print "with pineapple?"
- If it's not the string "pizza" print "I want pizza!"
Solution
#!/usr/bin/env bash [[ ${1} == "pizza" ]] && echo "with pineapple?" || echo "I want pizza!" - Basic Date
Objectives
- Write a script that will put the current date in a file called "the_date.txt"
Answer
Objectives
- Write a script that will put the current date in a file called "the_date.txt"
Solution
#!/usr/bin/env bash echo $(date) > the_date.txt - Count Chars
Objectives
- Read input from the user until you get empty string
- For each of the lines you read, count the number of characters and print it
Constraints
- You must use a while loop
- Assume at least three lines of input
Answer
Objectives
- Read input from the user until you get empty string
- For each of the lines you read, count the number of characters and print it
Constraints
- You must use a while loop
- Assume at least three lines of input
Solution
#!/usr/bin/env bash echo -n "Please insert your input: " while read line; do echo -n "$line" | wc -c echo -n "Please insert your input: " done - Directories Comparison
Objectives
- You are given two directories as arguments and the output should be any difference between the two directories
Answer
Objectives
- You are given two directories as arguments and the output should be any difference between the two directories
Solution 1
Suppose the name of the bash script is
dirdiff.sh#!/bin/bash if test $# -ne 2 then echo -e "USAGE: ./dirdiff.sh directory1 directory2" exit 1 fi # check for the checksums. # If both the checksums same, then both directories are same if test `ls -1 $1 | sort | md5sum | awk -F " " '{print $1}'` == `ls -1 $2 | sort | md5sum | awk -F " " '{print $1}'` then echo -e "No difference between the 2 directories" exit 0 fi diff -q $1 $2Solution 2
With gnu find, you can use diff to compare directories recursively.
diff --recursive directory1 directory2 - Empty Files
Objectives
- Write a script to remove all the empty files in a given directory (including nested directories)
Answer
Objectives
- Write a script to remove all the empty files in a given directory (including nested directories)
Solution
#! /bin/bash for x in * do if [ -s $x ] then continue else rm -rf $x fi done - Shell Scripting - Factors
Objectives
Write a script that when given a number, will:
- Check if the number has 2 as factor, if yes it will print "one factor"
- Check if the number has 3 as factor, if yes it will print "one factor...actually two!"
- If none of them (2 and 3) is a factor, print the number itself
Answer
Objectives
Write a script that when given a number, will:
- Check if the number has 2 as factor, if yes it will print "one factor"
- Check if the number has 3 as factor, if yes it will print "one factor...actually two!"
- If none of them (2 and 3) is a factor, print the number itself
Solution
#!/usr/bin/env bash (( $1 % 2 )) || res="one factor" (( $1 % 3 )) || res+="...actually two!" echo ${res:-$1} - Files Size
Objectives
- Print the name and size of every file and directory in current path
Note: use at least one for loop!
Answer
Objectives
- Print the name and size of every file and directory in current path
Note: use at least one for loop!
Solution
#!/usr/bin/env bash for i in $(ls -S1); do echo $i: $(du -sh "$i" | cut -f1) done - Great Day
Objectives
- Write a script that will print "Today is a great day!" unless it's given a day name and then it should print "Today is
"
Note: no need to check whether the given argument is actually a valid day
Answer
Objectives
- Write a script that will print "Today is a great day!" unless it's given a day name and then it should print "Today is
"
Note: no need to check whether the given argument is actually a valid day
Solution
#!/usr/bin/env bash echo "Today is ${1:-a great day!}" - Write a script that will print "Today is a great day!" unless it's given a day name and then it should print "Today is
- Shell Scripting - Hello World
Objectives
- Define a variable with the string 'Hello World'
- Print the value of the variable you've defined and redirect the output to the file "amazing_output.txt"
Answer
Objectives
- Define a variable with the string 'Hello World'
- Print the value of the variable you've defined and redirect the output to the file "amazing_output.txt"
Solution
#!/usr/bin/env bash HW_STR="Hello World" echo $HW_STR > amazing_output.txt - It's Alive!
Objectives
- Write a script to determine whether a given host is down or up
Answer
Objectives
- Write a script to determine whether a given host is down or up
Solution
#!/usr/bin/env bash SERVERIP=<IP Address> [email protected] ping -c 3 $SERVERIP > /dev/null 2>&1 if [ $? -ne 0 ] then # Use mailer here: mailx -s "Server $SERVERIP is down" -t "$NOTIFYEMAIL" < /dev/null fi - Number of Arguments
Objectives
- Write a script that will print "Got it:
" in case of one argument - In case no arguments were provided, it will print "Usage: ./
" - In case of more than one argument, print "hey hey...too many!"
Answer
Objectives
- Write a script that will print "Got it:
" in case of one argument - In case no arguments were provided, it will print "Usage: ./
" - In case of more than one argument, print "hey hey...too many!"
Solution
#!/usr/bin/env bash set -eu main() { case $# in 0) printf "%s" "Usage: ./<program name> <argument>"; return 1 ;; 1) printf "%s" "Got it: $1"; return 0 ;; *) return 1 ;; esac } main "$@" - Write a script that will print "Got it:
- Sum
Objectives
- Write a script that gets two numbers and prints their sum
- Make sure the input is valid (= you got two numbers from the user)
- Test the script by running and passing it two numbers as arguments
Constraints
- Use functions
Answer
Objectives
- Write a script that gets two numbers and prints their sum
- Make sure the input is valid (= you got two numbers from the user)
- Test the script by running and passing it two numbers as arguments
Constraints
- Use functions
Solution
#!/usr/bin/env bash re='^[0-9]+$' if ! [[ $1 =~ $re && $2 =~ $re ]]; then echo "Oh no...I need two numbers" exit 2 fi function sum { echo $(( $1 + $2 )) } sum $1 $2