Some Odds and Ends, Shell Scripting

Creating a File, Editing a File, Viewing a File

What command did we use to create a file?

touch name_of_file.txt

What command did we use to edit a text file?

nano name_of_file.txt

What command(s) could we use to show a text file?

cat name_of_file.txt 
# (also less and more)

Permissions

How do we show the permissions associated with a file?

ls -l name_of_file.txt

What do the permissions mean?

What command do we use to change permissions ?

chmod u+x name_of_file.sh 

Permissions Continued

What permissions does the following line give/remove?

chmod u-w name_of_file.sh 

removes write from user

What permissions do we have to give a file so that we can “run” it?

chmod u+x name_of_file.sh 

Running Scripts

How do we run a file that we made executable?

./name_of_file.sh

What does dot mean again?

The current directory

So what do you think ./ does?

In the directory I’m currently in… try to execute the following file

Running Scripts Continued

If we change to /, we’ll see that our command will no longer work to run the script.

However, we can use the full path to the script to run it! (Notice, there’s no dot at the beginning)

/full/path/to/name_of_file.sh

A Few Odds and Ends

Environment Variables

environment variables - are dynamic named values that affect the way processes (programs) run on your computer. for example, they may specify:

env

env shows the list of current environment variables and their values

env

Setting and Using Environment Variable

setting

MYVAR="some value"

using

echo $MYVAR

Common Environment Variables

echo $PATH

ps

Show all running processes…

ps aux

Look for a specific process…

ps aux | grep -i program_to_find

The first number after username is the process ID

bzuckerman       34930   0.0  

kill

….and when you have a process id, you can kill that program!

kill 12345

Shell Script Arguments

You can pass arguments to your shell scripts (just like commands like ls, cd, etc.):

./myscript.sh hello hi

Within your .sh file (your shell script), you can access these values by using $1, $2, etc … with each number corresponding to an argument; it starts with $1 as the first argument (the one closest to the command).

# using variables in your shell script
echo $1
echo $2

Shell Scripts - Using Variables

You can use variables as part of longer strings. For example, if we called our shell script by writing:

./myscript.sh example

Within the script:

echo "counting words, lines, bytes for ya!"
wc $1.txt

… would count the words in example.txt

Shell Scripts and For Loops

You can use the following syntax to repeat code. Here $i is a variable that can be used… and it represents each number from 1 through 3.

for i in {1..3}
do
   echo "Counting $i"
done