subprocess

linux geek/dad

subprocess RSS Feed
 
 
 
 

Bash Tip #2

bash-tip-2

Getting around

Sure… there’s “cd” to change directories and tab completion. But there’s more than that.  Here’s some other tips for getting around quickly in a Bash shell.

First, with “cd” there are some built in shortcuts. Most know of “~”. “~” expands to the current users homedir.

  • cd ~
  • cd ~/.kde
  • cd ~/Desktop

There’s also “-”. “-” expands to the variable of $OLDPWD, which is always the previous directory you were just in.

  1. cd /usr/local (change to /usr/local)
  2. cd ~ (change to users home dir)
  3. cd - (pops you back to /usr/local)

Bash bang commands can be used for shortcuts too.

  • !! = last line in history
  • !* = all args from last line in history
  • !$ = last arg from last line in history
  • !^ = first arg from last line in history

I really only use !$ with the cd command. Here’s some examples, although some not really useful. Just to give you an idea of what it does:

  1. which php (maybe it outputs /usr/local/bin/php)
  2. `!!` /path/to/php_script.php (executes php on the script)
  1. ls /usr/local/src
  2. cd !$ (cd’s to /usr/local/src)
  1. ls *.gz *.txt *.bz2 (do a quick scan on the files listed, confirm they’re the right ones)
  2. rm !* (remove ‘em all)

There’s also the Alt-. (that’s alt + period) shortcut. This will cycle through the last arg of all commands in your bash history. Try it out, just keep hitting alt-. over and over. Can be quite useful.

“pushd” and “popd”. These are great for using in scripts. “pushd” puts a directory on a stack and moves you to that directory. “popd” pops your current directory off the stack and moves you to the directory under it. Example:

hadley@rhadley-laptop:~$ pwd
/home/rhadley
rhadley@rhadley-laptop:~$ pushd /usr/
/usr ~
rhadley@rhadley-laptop:/usr$ pushd /usr/local/
/usr/local /usr ~
rhadley@rhadley-laptop:/usr/local$ pushd /etc/
/etc /usr/local /usr ~
rhadley@rhadley-laptop:/etc$ popd
/usr/local /usr ~
rhadley@rhadley-laptop:/usr/local$ popd
/usr ~
rhadley@rhadley-laptop:/usr$ popd
~
rhadley@rhadley-laptop:~$ popd
bash: popd: directory stack empty
rhadley@rhadley-laptop:~$

Well… my brain is fried and it’s too late in the day for extra caffeine, so that’ll have to be it. But, look here for tips on making your tab completion more powerful. It’ll even complete command line arguments for commands that support it.

One Response to “Bash Tip #2”

  1. 1
    benarwin:

    Great tips! I learned a few things. One more “!” shortcut is you can type “!” followed by one or more letters and it will execute the most recent command in your history that began with those letters.

    For example:

    # telnet google.com 80
    # test

    # !t (executes 'test')
    # !tel (executes 'telnet google.com 80')

    # !tes (executes 'test')

Leave a Reply

Recent Posts

Links

Meta