Scripting Basics Flashcards
(12 cards)
How would you create a script that uses python?
!/usr/bin/python
print(‘Hello, World!’)
What is the appropriate way to create a variable?
print the variable
How would you add the variable and put a suffix on it?
THIS_VARIABLE=’this’
echo “I like $THIS_VARIABLE stuff”
echo “I like ${THIS_VARIABLE}s. oops one extra ‘s’”
Create a variable that contains the output of hostname and then print the variable
SERVER_NAME=hostname
echo ‘You are running this script on ${SERVER_NAME}’
or
SERVER_NAME=$(hostname)
What can variables contain?
What can a variable start with?
digits, letters and underscores
They can start with Letters or Underscores but no digits
What should you do to create a test?
Create a test to see if /etc/passwd exists
What does this return
Show all test you can perform
Read the manual for tests
[ -e /etc/passwd ]
This returns a 0 if it exists
If it doesn’t exist it returns a 1 if it exists
help test
man test
Write a script to print two things if /etc/passwd exists
Create one for a variable you create is equal to ‘bash’
MY_VAR=’bash’
if [ -e /etc/passwd ]
then
echo ‘this’
echo ‘that’
fi
if [ ‘$MY_VAR’ = ‘bash’]
then
echo ‘this’’
else
echo ‘that’
fi
Should you enclose variables in quotes?
Yes, this is to prevent unexpected side effects when performing conditional tests.
When would you use elif?
Elif is used if instead of if because it won’t run unless the first if fails. If on the other hand will run everytime.
Use a for loop
for COLOR in red green blue
do
echo ‘The color is $COLOR’
done
What are Positional Parameters?
Use a positional argument in a script
Location of words in you commands. Parameter here just means word. From start to finish you will have $0 - $9
View the below command:
script.sh parameter1 parameter2 parameter3
script.sh $0
parameter1 $1
parameter2 $2
parameter3 $3
REMEMBER TO USE DOUBLE QUOTES
#!/bin/bash
echo “Locking password for $1”
passwd -l $1
./script.sh delsinm <- delsinm is parameter $1
YOU COULD EVEN JUST ASSIGNE IT TO A VALUE
USER=$1
How would you create a for loop to cycle through all users that you’ve added as positional arguments
for USER in $@
do
passwd -l $USER
done
How would you collect the input from someone asking for their username and storing it in a variable called USER
read -p “Enter a user name: “ USER
echo “Archiving $USER”