18.01.2020 Views

Working with Linux

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

of the current working directory (or CWD) variable. You see here that we are using nested

subshells in order to achieve this:

CWD=$( cd "$(dirname "${BASH_SOURCE[0]}" )/" && pwd )

cd ${CWD}

Next, we will source the util script, so that the library functions are exported into memory. Then, we

can access them from the current script:

source ${CWD}/lib/util.sh

Let's add a simple call to our getarg function using a subshell, and search for the cmd argument.

Also, let's echo what we've found, so that we can test our script:

CMD=$(getarg cmd $@)

echo ${CMD}

The next thing we need to do is to give the script execution rights using the chmod command. Also, in

order to run the script from anywhere, the bin folder must be in the PATH variable. Echo the variable

and check that the bin folder is there and, if not, update the variable in ~/.zshrc.

Let's test the script by reading a command line parameter with the getarg function and echoing it.

If you are searching for the iputils command in the terminal using tab for autocomplete and the

command doesn't seem to exist, that is probably because you need to tell zsh to reload its path

commands. To do this, issue the "rehash" command.

Now run:

iputil --cmd ip

This should work from within any folder, and it should print ip on the screen.

Now that we've verified everything is alright, let's write some code for our command line arguments.

If we run the script with the --cmd ip flags, the script should print that on the screen. This can be

done with the already-familiar case statement. Here we also want to pass in another argument, --

iface, to get the interface that's needed for printing the IP. It's also a good practice to add a default

case and echo a message saying invalid argument:

case ${CMD} in

ip)

IFACE=$(getarg iface $@)

print_ip ${IFACE}

;;

publicip)

get_public_ip

;;

*)

echo "Invalid argument"

esac

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!