24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

cathy ~> grep -c false /etc/passwd<br />

7<br />

cathy ~> grep -i ps ~/.bash* | grep -v history<br />

/home/cathy/.bashrc:PS1="\[\033[1;44m\]$USER is in \w\[\033[0m\] "<br />

With the first command, user cathy displays the lines from /etc/passwd containing the string root.<br />

Then she displays the line numbers containing this search string.<br />

With the third command she checks which users are not using bash, but accounts with the nologin shell are<br />

not displayed.<br />

Then she counts the number of accounts that have /bin/false as the shell.<br />

The last command displays the lines from all the files in her home directory starting with ~/.bash,<br />

excluding matches containing the string history, so as to exclude matches from ~/.bash_history which<br />

might contain the same string, in upper or lower cases. Note that the search is for the string "ps", and not for<br />

the command ps.<br />

Now let's see what else we can do with grep, using regular expressions.<br />

4.2.2. Grep and regular expressions<br />

If you are not on Linux<br />

We use GNU grep in these examples, which supports extended regular expressions. GNU grep is the<br />

default on Linux systems. If you are working on proprietary systems, check with the -V option which<br />

version you are using. GNU grep can be downloaded from http://gnu.org/directory/.<br />

4.2.2.1. Line and word anchors<br />

From the previous example, we now exclusively want to display lines starting with the string "root":<br />

cathy ~> grep ^root /etc/passwd<br />

root:x:0:0:root:/root:/bin/bash<br />

If we want to see which accounts have no shell assigned whatsoever, we search for lines ending in ":":<br />

cathy ~> grep :$ /etc/passwd<br />

news:x:9:13:news:/var/spool/news:<br />

To check that PATH is exported in ~/.bashrc, first select "export" lines and then search for lines starting<br />

with the string "PATH", so as not to display MANPATH and other possible paths:<br />

cathy ~> grep export ~/.bashrc | grep '\

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

Saved successfully!

Ooh no, something went wrong!