8/06/2020

The TAR command | Bash Basics


If you are familiar with ZIP, then you will be familiar with TAR. Basically, this is used to archive files into a single, hopefully, smaller, file. Sometimes you will hear these referred to as a “tarball”.

Figuring out what is in a TAR Archive

So normally when you are provided with a “tarball”, you go get it and then you extract it onto your system. This raises the questions, where will the files be created and what will be created? We can inspect the .tar file to determine what is in it. Remember that when we are working with TAR, we want it to be Verbose and so we add the v flag so we can see what it is doing. In the case of listing the contents of the archive, adding verbose or v is the same as asking for a long listing in the ls command by adding -l.
tar --list --verbose --file 
Ok, let’s get real, no one does this; this is what it would look like if you read the man page and decided that you wanted to type all of the things. I am lazy and I like to get things done with the least amount of typing on my part. What you see here is the same as this:
tar -tvf 
The only odd thing here is that --list is replaced by -t and then we can add all the flags to the same - statement. This means that for the rest of the examples I will show you the shorthand and you can decide how you want to do it. So now let’s look at some actual output.
$ tar -tvf ./example.tar 
drwxr-xr-x  0 mmcclaren staff       0 May  2 14:37 ./example/ 
-rw-r--r--  0 mmcclaren staff     210 May  2 14:23 ./example/._examplefile1 
-rw-r--r--  0 mmcclaren staff     899 May  2 14:23 ./example/examplefile1 
-rw-r--r--  0 mmcclaren staff     210 May  2 14:23 ./example/._examplefile2 
-rw-r--r--  0 mmcclaren staff   15033 May  2 14:23 ./example/examplefile2 
-rw-r--r--  0 mmcclaren staff     210 May  2 14:23 ./example/._examplefile3 
-rw-r--r--  0 mmcclaren staff   14957 May  2 14:23 ./example/examplefile3 
In this case, we can see that all of the example files were included in an example directory. This means that when we extract this, we will get that directory in the output. If the path is only the files and there is not a directory included, then the files will end up in the directory that you are in, unless you specify an extraction point.

Extracting a TAR Archive

So now that we know what is in there, we want to get it out of there. This is a matter of running the eXtract flag and the File flag.  Remember that we can add the Verbose flag so that we can see what it is working on.
 $ tar -xvf ./example.tar  
 x ./example/ 
 x ./example/._examplefile1 
 x ./example/examplefile1 
 x ./example/._examplefile2 
 x ./example/examplefile2 
 x ./example/._examplefile3 
 x ./example/examplefile3 
In this example, we extract the files into the example directory.
 $ ls -l ./example 
 total 72 
 -rw-r--r--@ 1 mmcclaren  staff    899 May  2 14:23 examplefile1 
 -rw-r--r--@ 1 mmcclaren  staff  15033 May  2 14:23 examplefile2 
 -rw-r--r--@ 1 mmcclaren  staff  14957 May  2 14:23 examplefile3 
If we wanted to indicate where we wanted the archive extracted, this would require the addition of the -C flag and a location as an argument. Think of this as “copy” the extracted files to the location indicated.
 $ tar -xvf ./example.tar -C ./location 
 x ./example/ 
 x ./example/._examplefile1 
 x ./example/examplefile1 
 x ./example/._examplefile2 
 x ./example/examplefile2 
 x ./example/._examplefile3 
 x ./example/examplefile3 
 $ ls -l ./location 
 total 0 
 drwxr-xr-x  5 mmcclaren  staff  160 May  2 15:08 example 
And the last thing that I want to talk about is extracting only one file from the archive. This takes the form of tar -xf ( archive name ) ( file name ) as in this example.
 $ tar -xvf ./example.tar ./example/examplefile2 
 x ./example/examplefile2 
 $ ls 
 example example.tar location 
 $ ls ./example 
 examplefile2 

Creating an Archive

Whew, this is a long one! We cannot leave, though, without knowing how to create an archive. The simplest way is to point TAR at a directory and use the -c flag for Create in the form of:
tar -cf  
This is how the example archive that we have been using was created:
 $ tar -cvf example.tar example 
 a example 
 a example/examplefile1 
 a example/examplefile2 
 a example/examplefile3 
 $ tar -tf ./example.tar  
 example/ 
 example/._examplefile1 
 example/examplefile1 
 example/._examplefile2 
 example/examplefile2 
 example/._examplefile3 
 example/examplefile3 
One last thing: let’s add a file to an existing archive. The -r flag is used to append to the directory and it takes the same syntax as “create”; the name of the archive and then the file.
$ tar -rf example.tar examplefile4 
$ tar -tf example.tar
example/
example/._examplefile1
example/examplefile1
example/._examplefile2
example/examplefile2
example/._examplefile3
example/examplefile3
examplefile4
As you can see, the examplefile4 was added to the previous archive that we have been using.

How to exit from VIM (VI) ?

Have you or a loved one ever had to reboot your computer to get out of a read-only file in VIM?

  • Are you responsible for a Linux system or set of systems where a graphical editor or adding new editors is prohibited?
  • Are you taking an online training course where all the labs use the VIM editor, and it’s driving you crazy?
  • Do other Open Source Pros tease you about not knowing VIM?
This short tutorial will help you get past the main issues you might encounter in quitting VIM. 

Use this tutorial to safely quit VIM, without the headaches

First off, you need to know what user you are when you edit files with VIM, so at the command line enter the id command:

IMPORTANT: One of the keys to not getting stuck in VIM is to never edit a root-only file as a regular user.  If you are the system admin, look into using the sudo command to allow editing root-only files from a regular account safely!

If you are in VIM and cannot seem to quit, we’ve got your back!  Relax, grab a drink of water, and let’s walk through a few very common scenarios.
Scenario #1
You are editing a root-only file as a regular user, have made changes to the file/buffer and it won’t let you out, showing you a message like this:
Solution #1
Press the ESC key twice or until you hear the “error bell”, then press :qa! which will force quit all open files/buffers and take you back to the command line.
Scenario #2
While trying to quit VIM with the keystrokes :q, you suddenly find the lower portion of your screen looks like a history list of the commands you’ve issued recently in VIM, and it freaks you out.
Solution #2
You have accidentally used the keystrokes q:, which opens up a Lastline or CommandLine history mode window that you could choose previous commands from to execute them again.  You can close this by carefully pressing :q again, which puts you back into Command/Normal Mode and you can quit as you would normally.
Scenario #3
You have tried to force-quit the file/buffer using :q! and suddenly you find yourself in what appears to be the command line, but it’s telling you that the q: command is not found.
Solution #3
You’ve flipped the keystrokes around and entered :!q, which is telling the VIM editor that you want to run an external command (:!command) and of course it won’t find the q: command, so all you get is an error!  Press ENTER and you’ll be back inside VIM and can exit normally, just be careful to type exactly what you want!

VI Shortcuts & Commands For Newbies

This is a collection of some of the basic VI commands and shortcuts for newbies. You’ll find yourself needing this if you are coding or scripting inside of the unix/linux command line using VI.
Command Mode: Accepts commands, which are usually in the form of individual letters. Example, a and i.
You can use h, j, k and I to navigate in similar ways as the up and down arrow. Not needed if you have an up and down arrow on your keyboard.
Yank – Term used to copy files. Use YY to yank text. Navigate to the line you wish to yank and type yy make sure you are in command mode.
2yy will yank 2 lines, 4yy will yank 4 lines. Precede the YY command with the number of lines you would like to yank.

– append text after cursor
– append text to end of current line
– Command will paste the yanked line(s) contents starting on the line after your cursor.
– Upper case P will paste the yanked line(s) starting on the line before our cursor
– Takes you to specified line
– Takes the cursor to the top of the page
– Takes the cursor to the bottom of the page
– inserts a new line below the line your cursor is on and inserts into insert mode for typing.
– undo any change, must be in command mode and only goes back one change.
– Move over one word at a time
Shift + G– Takes you to the bottom of the page
Page up and down in VI
Shift + f Page down (forward)
Shift + b page up (backward)
note* The keyboard page and and page down keys work the same
Change text – cc-allows you to change the entire line (basically removes the line and inserts into insert mode) cw to replace just one word on the line the current word your mouse is over.
Search – search forward type / and ? searches backwards; both followed immediately by the term to search for.
:%s/foo/bar will replace the first occurrence of foo with bar, operating on every line in the buffer.
:%s/foo/bar/g will replace every occurrence of foo with bar, operating on every line in the buffer.
:s/foo/bar will replace the first occurrence of foo with bar, operating on the current line.
:s/foo/bar/g will replace every occurrence of foo with bar, operating on the current line.

Also very helpful is the /c flag – it will allow you to confirm each replacement match, depending on the above criteria for searching.

– moves to next occurrence of search string
– move to next occurrence of search string in opposite direction
Ex mode: Enter ex mode from command mode with “:”. Use this to save or manipulate files. This mode is also referred to as colon commands
Replace text – :%s/fine/ one – this replaces all occurs of “fine” with “one”
% represents “global changes to all occurrences” replace to a line number, ending line number of comma.
:= – returns number of current line
:w filename – writes contents of file to a new filename.
Insert Mode: Enables you to insert and edit text. The Esc key exits insert mode and returns you back to command mode.
– enters the insert mode to replace text not insert text. It will replace text until it hits a space. After a space you must start typing over the text for it to apply or it will just push text down.
– used to insert text and not replace it. Pushes existing text down.
ZZ– Save and quit in 2 key strokes instead of wq!
:w – Saves changes without quitting
:wq – Saves changes and quits
:q! – Quits without saving changes.
:e /file.txt will load the new file.txt into the vi editor for editing. This will only occur if the current changes to the current file being edited are saved.
:r allows you to bring contents of an old file into a new one.
:! Allows you to run shell commands from within vi. Such as :!mkdir tes

The Linux find Command

We get so focused on the super-advanced things that Linux can do, that we tend to forget about or glaze over the mundane.  Linux’s find command falls into that category for me.
First of all, remember that Linux is case sensitive. This means that “TEST”, “test”, “Test”, and “TesT” all register as completely different files. Run find –help for all of the available options. To see everything, including the things I’m not going to cover in this brief article, remember you can always man find.
Examples:
Find all files in the entire system that are named test.txt:
find / -name “test.txt”
Find all files in the /etc directory not named test.txt:
find /etc/ -not -name “test.txt”
Find all character devices on the system:
find / -type c
Find all directories called log:
find / -type d -name “log”
Find all files in the /usr/bin directory or subdirectories that are larger than 27,000 bytes:
find /usr/bin/ -size +27000c or find /usr/bin -size +27k
Find all files in the /usr/bin directory or subdirectories that are larger than 1 megabyte:
find /usr/bin/ -size 1M
Find all files created more than a day ago:
find / -mtime 1
Find all files create less than a day ago:
find / -mtime -1
Find all files owned by the user named “chad”:
find / -user chad
Find all files in the /etc directory owned by the user root, and paginate:
find /etc/ -user root | more
Find all files in the /usr/bin directory with the user permissions 755:
find /usr/bin/ -perm 755
Find all files called test.txt and set their permissions to 700:
find / -name “test.txt” -exec chmod 700 {} \;
In Linux, the general rule is “No news is good news,” which means that when a command completes successfully, you will likely receive no command line confirmation or other feedback. If you don’t get a response to a command, it likely completed exactly as you expected.
The more command will cause the output to pause after it fills a page and waits for you to hit the space bar before continuing. There is also a less command that will allow you to scroll back and forth through the output using arrow keys.
The which command allows you to find the version of a command that will be executed if invoked. This is useful for locating the executable file, especially if the behavior is not what you expected. For instance, to find out which python executable would be invoked, run:
which python
The locate command can also help you find files but relies on a database rather than looking directly at the file system. The two can easily be out of sync. To synchronize the locate’s database, run the command (as root):
updatedb

Linux Commands For Beginners: SUDO

Sudo, the one command to rule them all.  It stands for “super user do!”  Pronounced like “sue dough” As a Linux system administrator or power user, it’s one of the most important commands in your arsenal.  Have you ever tried to run a command in terminal only to be given “Access Denied?”  Well this is the command for you!  But, with great power comes great responsibility!  It is much better than logging in as root, or using the su “switch user” command.  Read on to see what sudo can do for you!

SUDO: What is it good for?

So what does sudo actually do?  If you prefix “sudo” with any linux command, it will run that command with elevated privileges.  Elevated privileges are required to perform certain administrative tasks.  Someday you may wish to run a LAMP (Linux Apache MySQL PHP) server, and have to manually edit your config files.  You might also have to restart or reset the Apache web server or other service daemons.  You even need elevated privileges to shutdown or restart the computer.  “Hey, who turned this thing off?!”
If you are familiar with Windows, it is very similar to the Windows User Account Control dialog box that pops up when you try to do anything important, just not as friendly.  In Windows, if you try to perform an administrative task, a dialog box asks you if you wish to continue (“Are you really sure your want to run that program you just clicked on?”).  The task is then performed.  On a Mac, a security dialog box pops up and you are required to type in your password and click OK.
It is more of a dramatic story in Linux.  Things might behave quite strangely without the proper permissions.  The important config file you were editing may not save correctly.  A program you installed may simply refuse to run.  That awesome source code you downloaded and need to compile, wont.  You might even be lucky enough to given an “Access Denied” or another friendly error message. All your worst fears have come true, but all you needed to do was ask for permission!  That is why we want to remember to ask for superuser permissions upfront like this:
sudo reboot
Watch what happens in this screenshot if we don’t first elevate our permissions with sudo:
reboot
First we use the reboot command to try and reboot the system.  The command fails citing: “must be superuser”.  We then try with sudo reboot.  Sudo asks for your user password.  Note that it is asking for your password, not the root password.  Finally we see the broadcast message that the system will be rebooted now.  Sudo is like saying the magic word.  It might as well be named opensesame or abracadabra or even bippityboppitybacon.
sandvich

Why is it better than the alternative?

Sudo is the best and safest way to elevate privileges.  Lets take a look at another way of doing things.  The switch user command, “su” will ask you for the root password and give you a superuser prompt, signified by the # symbol.  That # symbol means “DANGER! YOUR LOGGED IN AS ROOT!”  The first command you issue may go well.  But your forgetfulness will cause you to stay logged in as root.  One bad typo and BAM!  You erased the entire hard drive instead of that fake mp3 you downloaded.  The cat decides to lay on your nice warm laptop.  POOF!  Your web server and home business are gone!  With the sudo command, you have to enter in “sudo” before every command.  Thus you don’t have to remember to switch back to regular user mode, and fewer accidents will happen.

The Sudoers File

This file is the seedy underbelly of sudo.  It controls who can use the sudo command to gain elevated privileges.  It is usually located at /etc/sudoers.  The best and safest way to edit this file is by using the visudo command.  This command will start the vi editor with elevated privileges so that you can edit the file and save it.  It also will put a filelock on the sudoers file so that no one else can edit it.  Once your done editing it, it will parse the file for simple errors.  It is a much safer way of editing the sudo file than just using any old text editor.
This file contains many parameters.  You can specify which users of which groups can perform what commands.  We are simply going to grant ourselves access to sudo by adding:
username   ALL=(ALL)       ALL //gives user "username" sudo access
%wheel     ALL=(ALL)       ALL //Gives all users that belong to the wheel group sudo access
at the bottom.  Now the specified username will be able to use all root privileges. You can also allow a user or group to have sudo access to only specific services or servers in replace of the ALL parameter, but, that’s a topic for another day.

Some Options

Like any good command there are a few nifty options to make sudo, do more!
sudo –b will run the command in the background.  This is useful for commands that display a lot of output as they are running.
sudo –s will run the shell specified with elevated privlages, giving you the # prompt (don’t forget to exit!)
sudo su – will make you the root user and load your custom user environment variables.

Changing The Time Zone In Linux (Command Line)

There are several different ways to manage time in Linux. This quick tip will show you how to quickly change the local time to the correct time zone for the server. In this Linux tip I’ll show you how to change the localtime to your (or a) current time zone.
Location of the local time file
Linux looks at /etc/localtime to determine the current time of your machine. This can either be a symbolic link to the correct time zone or a direct copy of the time zone file.

Timezone files are located in /usr/share/zoninfo/
For this tip we will assume your server is located in America and will be under the Chicago CST zone.
I change the Linux time zone by copying or making a symbolic link to from /usr/share/zoneinfo/America/Chicago to /etc/localtime
Two methods to do this
cp /usr/share/zoneinfo/America/Chicago /etc/localtime

ln -s /usr/share/zoneinfo/America/Chicago /etc/localtime

Type w to change the new time and you’re done!

Some things I wish I knew earlier about the Linux command line

We all learn new things over time as we use applications with a vast amount of possibilities. Of course, some of those things would have been so useful if we had known them earlier. Here are 10 command line tricks that I wish I had learned much sooner.
Note: these tricks apply to bash, which is the default shell on most Linux systems. If you’re using a different shell, they may not work for you. If you don’t know which shell you have, it’s probably bash, so go ahead and try them!

1.) Ctrl+U and Ctrl+Y.
Do you know that moment when you’re typing a long command, and then suddenly realize you need to execute something else first? Especially when working over an SSH connection, when you can’t easily open a second terminal on the same machine, this can be very annoying. Solution: ensure your cursor is at the end of your current command (shortcut: Ctrl+E), press Ctrl+U to get a clean line, type the other command you need to execute first, execute it, then press Ctrl+Y and voila! Your long command is back on the line. No mouse needed for copying, just quick hotkeys.
2.) Ctrl+R.
Speaking of long commands: when you need a previously used command again but don’t want to retype it because it’s long or complex, there’s a good chance it’s stored in your history file. The quickest way to retrieve and execute it is to press Ctrl+R and type a few characters that are part of your command. For example:
for pid in $(pidof plugin-container); do file /proc/”$pid”/fd/* |
fgrep /tmp/Flash | cut -d: -f1 | xargs mplayer; done
Now that’s a command that I wouldn’t like to type every time I use it. It’s a one-liner to play the temporary media files Flash secretly stores when you play, for example, a YouTube movie. When I want to execute this monster, I only type the following:
Ctrl+R
“pidof”
Enter
The stuff between quotes is literally typed, as in I press p, then i, and so on. The reason this works is that I almost never use the pidof command except in this one-liner, so the most recent command executed that contains “pidof” is almost always the right one. However, suppose I did recently execute a different command containing “pidof”. By repeatedly pressing Ctrl+R after typing “pidof” but before pressing Enter, I can cycle through the list of commands until I hit the one I meant to execute, and then press Enter. And, last but not least, you can still edit the command you found using Ctrl+R before hitting Enter; just press the right or left arrow to get out of the history search mode, and edit away!
3.) The screen command.
When working over an ssh connection, commands that take long to execute can seriously get in your way. You have to keep the connection open to allow the command to complete, which means that you can’t turn off your computer, and you can’t execute a different command without opening a second ssh connection or (temporarily) terminating the running command. Both annoyances melt away when you use screen.
The screen command allows you to run multiple terminal sessions inside a single terminal session, and manage the multiple sessions using hotkeys. Try it! Just execute “screen” in your terminal (install it first if necessary) and see an empty terminal opening. Now execute the command “sleep 9999”. This will take quite long and block your terminal. However, if you press Ctrl+A, let go of the keys, and then press C, you will get a fresh new terminal ready to take commands. The sleep command on the other terminal keeps running without being interrupted. To cycle between the two open terminals, use Ctrl+A N for next and Ctrl+A P for previous (remember to let go of all keys after pressing Ctrl+A). Finally, to shut down screen without interrupting the commands that are running, press Ctrl+A D for detach. You will return to your original terminal, and if it’s an ssh session, you can exit it without interrupting the commands running in screen. To get back to the screen terminals you opened before, execute “screen -R” for reattach. To exit a screen session, just exit all terminals in it as you would normally exit terminals (Ctrl+D).
For more information about screen, read its man page by executing “man screen”. It’s a very powerful tool that even allows multiple people to use a single terminal at the same time!
4.) The xargs command.
Whenever you want to execute a command on multiple files, or for every line of a certain file, xargs is the first tool to look at. Here’s an example:
find . -iname ‘*.php’ -print0 | xargs -0 svn add
Anyone who has ever worked with a version control system like svn probably knows the annoyance of having to svn add every newly created code file after a few hours of editing. This command does it for you in an instant. How does it work?
  1. “find . -iname *.php -print0” prints all files in the current directory (“.”) or its subdirectories that end in .php (case-insensitive) and separates them by null characters (“-print0”). The null character is never used in filenames, while a newline may be, so it is safer to separate by null characters.
  2. “xargs -0 svn add” receives the output of find on its standard input through the pipe (“|”), separates it by null characters (“-0”) and feeds the filenames as arguments to svn, after the “add” argument. It minds the limits the system imposes on the amount and size of command line arguments, and will run svn multiple times as necessary while still invoking it as few times as possible.
To find out more about xargs, read the man page by executing “man xargs”. Using xargs is safer and more versatile than using the -exec option of find. For ultimate versatility, however, use the slightly less elegant for loop, which is described in the second part of this list.
5.) Using bash as a simple calculator.
Sometimes you need to quickly do a calculation that is too large or too important to do using your head. When you’re working in a graphic environment, you might just fire up kcalc or gcalctool, but tools like that may not always be available or easy to find. Fortunately, you can do basic calculations within bash
itself. For example:
echo $((3*37+12)) # Outputs 123
echo $((2**16-1)) # Two to the power of sixteen minus one; outputs 65535
echo $((103/10)) # Outputs 10, as all these operations are integer
arithmetic
echo $((103%10)) # Outputs 3, which is the remainder of 103 divided by
10
The $((something))-syntax also allows bitwise operations, and as such it interprets the caret (“^”) as a bitwise operator. That’s why “**” is used for “to the power of”. The syntax also supports showing the decimal equivalent of a hexadecimal or octal number. Here’s an example:
echo $((0xdeadbeef)) # Outputs 3735928559
echo $((0127)) # Outputs 87
For more information, read the bash man page using “man bash” and search (using the / key) for “arithmetic evaluation”. If you want to do floating point calculations, you can use bc (might need to install first):
echo ‘scale=12; 2.5*2.5’ | bc # Outputs 6.25
echo ‘scale=12; sqrt(14)’ | bc # Outputs 3.741657386773
Note the setting of the scale variable. Using bc, you can perform floating point operations with any precision you like. The scale variable controls the amount of decimals behind the dot that are calculated. I used 12 here because kcalc uses that amount by default, but you can increase or decrease it as you like. Find out more about what bc can do by executing “man bc”. It even supports more advanced mathematical functions, such as the arctangent or the natural logarithm.
6.) Quoting.
To allow you to write awesome scripts, bash attaches a special meaning to many characters (like * & ; | { ! < [ # and a lot more). Sometimes, however, these characters are not to be interpreted in any special way, but just to be passed unmodified to some command. A commonly used example:
find . -iname ‘*.conf’
Notice the single quotes around “*.conf”. What if I forgot those? Bash would interpret the *.conf as a glob expression and expand it to all files ending in .conf in the current directory. This could prevent find from looking for all .conf files in subdirectories, causing unexpected results. Therefore, it’s a good habit to always quote anything that might contain special characters.
Note that only single quotes prevent every character from being interpreted; double quotes still allow bash to interpret some characters. When working with variables, double quotes come in handy to prevent word splitting. This is often used in scripting. An example:
#!/bin/bash
# This script renames a file to lowercase
newname=”$(echo -n “$1″ | tr ‘[A-Z]’ ‘[a-z]’)”
mv -i “$1” “$newname”
You can see quite a lot of double quotes in this script, and all of them are necessary to prevent trouble with certain filenames. You see, when a filename contains whitespace, bash splits the name on that whitespace when you leave variables unquoted. Suppose you have a file named “spaced name.txt”, you put it in a variable (“filename=’spaced name.txt'”), and then you try to move it to “unspacedname.txt” by executing “mv $filename unspacedname.txt”. You’ll get the error “mv: target `unspacedname.txt’ is not a directory”. This is because mv gets executed like this: “mv spaced name.txt unspacedname.txt”. In other words, mv will try to move two files, “spaced” and “name.txt” to “unspacedname.txt”, and fail because moving multiple files to a single destination is only allowed when the destination is a directory. Putting double quotes around “$filename” solves this issue.
So you see, quoting is a good habit to prevent your commands and scripts from doing unexpected things. Two final notes: you can’t quote variables using single quotes, because the dollar sign loses its special meaning between single quotes, and if you ever need to use a literal single quote in some command, you can do so by putting it between double quotes. Using ‘ between single quotes will not work, because even the backslash it not interpreted between single quotes.
7.) For loops.
Using xargs, you can run a command on a list of files. However, sometimes you’ll want to use more advanced functionality of bash on a list of files. For example, you might want to set up a pipe of commands, like this:
# Count the number of while loops in each of the php files in the
current directory
for file in ./*.php; do echo -n “$file”: ; grep ‘while’ “$file” | wc
-l; done
Let me explain what happens there part by part:
  1. “for file in ./*.php”: make a list of all the files ending in “.php” in the current directory, and for each of them, run the following code with the variable “$file” set to the filename.
  2. “do … done”: indicates the beginning and end of the code inside the for loop. Note that both of them have to start on a new line, which is why the semicolons are there. They count for starting a new line.
  3. “echo -n “$file”: “: print the filename, followed by a colon and a space, but not a newline (the “-n” option suppresses the default extra newline). The backslash makes sure the space is actually printed and not eaten away by bash.
  4. “grep ‘while’ “$file” | wc -l”: grep reads the file and prints only the lines containing the word “while”. These lines are piped to
    “wc -l”, which counts the amount of lines (word count with option lines).
As you can see, you can easily place multiple commands within the for loop; every bit of code between “do” and “done” is executed for every file. Imagine the possibilities, especially when you get to know more of the built-in bash functionality. Read on for an example of that.
8.) String manipulation.
There comes a time in the life of every serious bash user when some string manipulation is needed. For example, you might have a number of photos
of which the filenames start with “DSC”, and you’d like to replace that prefix with something more meaningful, like “Vacation2011”. Using a for loop as it was introduced above, you can do this in a flash (pun intended):
for file in DSC*; do mv “$file” Vacation2011″${file#DSC}”; done
How does this work? The for loop runs for every file in the current directory of which the name begins with “DSC”. For every such file, mv is executed to move the file to “Vacation2011”. The magic that strips “DSC” happens in “${file#DSC}”, where the “#” indicates that the string after it should be removed from the front of the contents of the variable before it. There also exist operations to strip from the back of the string (useful for removing file extensions), to search and replace in a string and to extract substrings. To learn more about string manipulation, visit Manipulating
Strings on TLDP
.
9.) Dynamic port forwarding.
Sometimes you need to access a website that’s only accessible from computers inside a certain network. Or, the other way around, sometimes you are in a certain network and you need unobstructed access to the internet, but some hyperactive firewall is in the way. If you have ssh access to a computer that does have the internet access you need, you can use it as an anonymous tunneling proxy without any additional tools. Just add the following option when you ssh into the server:
ssh -D user@remotehost
The -D option tells ssh to set up a dynamic port forward on local port . I like to use port number 1337, but almost any port between 1024 and 65535 will do. When you’ve logged in on the remote server, you can configure your browser to use localhost with the port number you specified earlier as a SOCKS proxy (SOCKS versions 4 and 5 are both supported). This setting is usually found in the same place as the other options for using a web
proxy. In Firefox, look under Preferences => Advanced => Network => Configure how Firefox connects to the Internet. Once you’re browsing over this SOCKS proxy, it will appear to the web as if the host you sshed into is browsing.
10.) Process substitution.
Ever wanted to diff the outputs of two commands quickly? Of course, you could redirect the output to a temporary file for both of them, and diff those files, like this:
find /etc | sort > local_etc_files
find /mnt/remote/etc | sort > remote_etc_files
diff local_etc_files remote_etc_files
rm local_etc_files remote_etc_files
This would tell you the differences between which files are in /etc on the local computer and a remote one. It takes four lines, however. Using process substitution, we can do this is just a single line:
diff <(find /etc | sort) <(find /mnt/remote/etc | sort)
What’s that <(…) syntax? It means “run the command inside it, connect the output to a temporary pipe file and give that as an argument”. To understand this more thoroughly, try running this:
echo <(echo test)
Instead of printing “test”, this will print something like “/dev/fd/63”. You see now that the <(…) part is actually replaced by a file. This file is a stream from which the output of the command inside <(…) can be read, like this:
cat <(echo test)
Now this does print “test”! Bash redirects the output of “echo test” to /dev/fd/, gives the path of that file to cat, and cat reads the output of echo from that file. The shortened diff command above does the same, only for two slightly more complicated commands. This technique can be applied in any place where a temporary file is needed, but it does have a limitation. The temporary file can only be read once before it disappears. There’s no use in saving the name of the temporary file. If you need multiple accesses to the output of a program, use an old-fashioned temporary file or see if you can use pipes instead.
Bonus!
Thought you would only get 10 tricks? Wrong :)! There’s one more thing I just can’t help but share with you. If you ever (are forced to) work with Windows, you don’t have to miss out on all of these tricks. You can ssh to remote hosts using PuTTY, which is a portable program, and copy files to and from servers with SSH access using WinSCP, which also has a portable version. And, to take it even further, you can use bash on Windows by installing Cygwin!

Popular Posts