Scripting Basics Flashcards
Write out the basic structure of a bash script
#!/bin/sh #this points to the intrpreter to use echo "Hello World!" exit 0 #The return value for the script
How do we make a script an executable
chmod +x name-of-script.sh
How do run a script
./name-of-script.sh
What type of file extension does a script need to be saved as
.sh
What is the shell used to run scripts
Bourne
If you want to use a different shell (e.g. zsh, bash), you need to update the script to know to use that environment.
Can you run a script that doesn’t have the opening #!/bin/sh
Yes. You can run it using the sh command.
What’s the comment character for Bourne scripting
#
Declare a shell variable
v1=”Hello World”
What type of value are shell variables
Strings.
Shell scripting does not support other type of variables
How do you use a variable once it’s declared
$variableName e.g. $v1
How do you determine the length of a string
${variableName} e.g. ${#v1}
What does a null value mean in shell scripting
An empty string
Explain the following variable modifier:
v2=${v1:-foo}
If v1 is not empty, use v1; else use the text ‘foo’
Explain the following variable modifier:
v2=${v1:=bar}
If v1 is not empty, use v1; else assign ‘bar’ to v1 and use it
Explain the following variable modifier:
v2=${v1:?}
If v1 is not empty, use v1; else exit with an error message
How would you store the output of a command into a variable?
You would create a vriable and then surround the command in backticks
num=echo $v1 | wc -w
How can you perform arithmatic since shell variables are stored as strings
Use the expr command
v2=3 #3 is stored as a string valueexp
expr $v2 + 1 #returns 4
Or you can use the following shorthand:
v3=$((v3 + 1)) #
What operators do we have to chain commands together
&& #If the first command runs, run the next one also
command1 && command2 # if command1 succeeds, run command2 also
|| #If the first command fails, run the next one
command1 || command3 # if command1 fails, run command3
What’s the syntax for grouping commands together
Wrap in curly braces. Seperate commands with a newline or semicolon. If a semi colon is used, ensure the is a space afterwards.
[ ‘id -u’ -eq 0 ] || { echo “root only!”; exit 1; }
Wildcard characters
? A single character
* Multiple Characters
Escape character
\
Home path characyer
~
Is there a difference between single quoutes and double quotes
Yes. Single quotes indicate literal assignment, Double quotes allows for enhanced features (e.g. escaped whitespaces, variable name exansion).
The backslash escape character works with double quotes, not single quotes.
When in doubt, go with double quotes.
How can you assign the output of a command to a variable
Use backticks.
e.g. dirlist=ls -alt