Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Saturday, 26 December 2009

How-To: Post to Twitter from Command-Line

This is a short tutorial explaining how to post to Twitter using command-line in Linux, without needing to even open up your web browser.

First, install the curl package:

sudo apt-get install curl

Next, create a script anywhere in your $PATH, for example twitter.sh inside ~/bin, where ~ is your home directory (make sure ~/bin is included in your $PATH variable, in case echo $PATH doesn't return it, edit ~/.bashrc and add a line like this: export PATH=/home/USER/bin/:$PATH).

The script twitter.sh should contain the following:

#!/bin/bash
curl -u USER:PASS -d status="$*" http://twitter.com/statuses/update.xml > /dev/null
echo "Message sent!"

Replace USER and PASS with your Twitter username and password, and then make the script executable:

chmod 755 ~/bin/twitter.sh

And now test it:

twitter.sh Hello, world! This is a test.

So just use it as:

twitter.sh YOUR MESSAGE

This should be all. Have a look at the screenshots below:

Running the twitter.sh script

Saturday, 22 August 2009

Tip of the Day: Prevent Exiting a Shell with Ctrl+D

A normal Bash shell with exit the current session when pressing ^D (Ctrl+D), but this can be avoided by editing the ~/.bashrc file and adding the following line:

export IGNOREEOF=1

This command will set the $IGNOREEOF variable to true, preventing a single combination of ^D to exit. In order to close the session, you can still use exit or double ^D.

Wednesday, 12 August 2009

5 Simple Bash Tips, Part III

This is the third article in the Bash tips series, you can find the other two here and here.

1. Use cd - to go to the previous working directory

cd - is the same as cd $OLDPWD, where the $OLDPWD variable holds the previous working directory. You can also alias this to something like:

alias back='cd -' # or alias back='cd $OLDPWD'

If you've just opened a new Bash session or sourced .bashrc, the $OLDPWD variable will be unset. Also, follow this discussion on reddit which is a great resource on this matter.

2. Make copies of files easier
This one is especially useful for creating backup files, but not only. To fasten up rename commands like mv file1 file1bak you can use something like:

mv file1{,bak}

Here, Bash will expand this command into mv file1 file1bak and execute it afterwards.

3. Search history backward or forward
This one is very popular due to its usefulness. Add the following two lines inside your .bashrc file:

bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward

Now type a command, for example ls, and then press the Up or Down arrows. You will see how it autocompletes the last ls commands. This will not change the default behaviour of Ctrl+P and Ctrl+N.

4. Use grep -e "-pattern" to search man pages for entries starting with -
This one is not necessarily a Bash tip, but you can use it to search man pages for entries that start with characters like -

man gcc | grep -e "-Wall"

5. Change the Bash prompt colour
You can customise your Bash prompt the way you like, including colours and what to display. Here's a simple example, just add this line at the end of .bashrc:

PS1="\[\033[1;33m\]$USER@$HOSTNAME$ \[\033[0m\]"

This will offer a nice yellow prompt like in the screenshot below:


Tuesday, 7 July 2009

5 Bash Tips, Part II

This article is a continuation to my other Bash-related post, 6 Bash Productivity Tips. Since that article gathered many useful comments and I bumped into several more over the net, here are 5 more tips and tricks. Although these may not be necessarily productivity-related, they will surely ease working in a Bash terminal and it may be worth knowing them. If you're not familiar with the terminal, command-line interface and Bash you can go ahead and read my introduction to Linux CLI.

Using Ctrl+R (reversed search)
Ctrl+R performs a reversed search in the history. For example, typing the command df -h | grep /dev/sda1, then pressing Ctrl+R and typing only df, the most recent command will be auto-completed and performed upon pressing Enter. Ctrl+R searches for occurences of what you type and returns the last command in which it finds it:

$ df -h | grep /dev/sda1
/dev/sda1 83G 65G 14G 83% /
(reverse-i-search)`df': df -h | grep /dev/sda1

Using !COMMAND
Where COMMAND is any command executed in the past or the beginning of a command. This calls the most recent command starting with COMMAND. For example:

$ for i in *.ogg; do vorbiscomment -l $i; done
...
$ ls
...
$ !for
for i in *.ogg; do vorbiscomment -l $i; done

In the above example, using !for followed by Enter executed the last occurence in the history which started with for.

Exit status: echo "$?"
This will return the exit status of the last executed command. It can prove useful in scripts. A command returns 0 if it ended successfully and a non-zero value otherwise:

$ cat /etc/motd | head -1
Linux debian 2.6.26-2-686 #1 SMP Sun Jun 21 04:57:38 UTC 2009 i686
$ echo "$?"
0
$ cat /etc/mots
cat: /etc/mots: No such file or directory
$ echo "$?"
1

Using !! with sudo
Here's a useful example of !! from one of the comments in the older post. !! will replace the last command, so using sudo !! will execute the last command preceding it with sudo. Very useful when performing commands which need root privileges and forgetting to precede them with sudo. Example:

$ apt-get update
E: Could not open lock file /var/lib/apt/lists/lock - open (13 Permission denied)
E: Unable to lock the list directory
$ sudo !!
sudo apt-get update

Run a specified command in history with !NUMBER
This will run command numbered NUMBER from history. Examples: !250, !1, etc. To view the history and the corresponding numbers, type history:

$ history | tail -3
534 for i in *.ogg; do vorbiscomment -l $i; done
535 history
536 history | tail -3
$ !534
for i in *.ogg; do vorbiscomment -l $i; done
Error opening input file '*.ogg'.

In the above example, command number 534 was executed when typing !534.

For other suggestions or corrections to these tips, please use the comments below.

Tuesday, 30 June 2009

Tip of the Day: Make a Memory Usage Script

Here's a simple memory usage script made in Bash, which will use the parsed output of free -tom utility. First, here is what the -tom argument stands for:

-t displays a line containing the total amount of memory (physical memory + swap)
-o disables the display of a buffer line
-m displays sizes in MB

Here goes the script, which outputs the total, used and free memory:

#!/bin/bash

# total memory
memt=$(free -tom | grep "Total:" | awk '{print $2}')
# used memory
memu=$(free -tom | grep "Total:" | awk '{print $3}')
# free memory
memf=$(free -tom | grep "Total:" | awk '{print $4}')
echo "Total memory: $memt MB"
echo "Used memory: $memu MB"
echo "Free memory: $memf MB"

You can put this in a file of your choice, say memory.sh, make it executable (chmod 755 memory.sh), put it inside ~/bin (or a directory of your choice) and then include that directory in your $PATH, so you'll be able to run the script just by typing memory.sh.

Sunday, 28 June 2009

6 Bash Productivity Tips

1. Use !!
Typing !! followed by Enter will bring back and execute the last command (same as Ctrl+P followed by Enter).

2. Use Emacs-like shortcuts
Emacs-like shortcuts make use of the Ctrl and Alt keys, and the big advantage of navigating and manipulating text in a Bash prompt is that you won't have to move your fingers away from the typing position (to access the arrow keys, or the Home, Page Up and Page Down keys). Notice that most of those work well inside manual pages too, or when using the Nano editor, or the less and more pagers.

Ctrl+D - or EOF (end-of-file) will quit the current Bash session
Ctrl+P - bring back the last command executed
Ctrl+N - bring the next command executed
Ctrl+U - delete all from the cursor to the left
Ctrl+K - delete all from the cursor to the right
Ctrl+B - go back one character
Ctrl+F - go forward one character
Alt+B - go back one word
Alt+F - go forward one word

3. Make manual pages coloured
I think this tip is a productivity tip because once a manual page is shown coloured, it is easier, clearer to read. Just add the following inside the ~/.bashrc file, where ~ is your home directory (notice that each line starts with export):

export LESS_TERMCAP_mb=$'\E[01;31m' # begin blinking
export LESS_TERMCAP_md=$'\E[01;38;5;74m' # begin bold
export LESS_TERMCAP_me=$'\E[0m' # end mode
export LESS_TERMCAP_se=$'\E[0m' # end standout-mode
export LESS_TERMCAP_so=$'\E[38;5;246m' # begin standout-mode - info box export LESS_TERMCAP_ue=$'\E[0m' # end underline
export LESS_TERMCAP_us=$'\E[04;38;5;146m' # begin underline

Then, type:

source ~/.bashrc

And try any manual page (e.g. man bash). Here's how a coloured man page looks like using the presets above:

Coloured man page

4. Use your own scripts
If you have basic knowledge of Bash scripting, you can create scripts and put them in a directory included in your $PATH. You can use something like ~/bin or ~/usr/bin, where ~ is your home directory.

5. Copy/paste using Shift+Insert
Although this one is not Bash-specific, it's very useful when you need to quickly copy/paste some text in your terminal. The same can be accomplished using the middle-click mouse button.

6. Use aliases
One of the powerful features of Bash is that it makes use of aliases. Those are usually short commands which perform some associated, longer command or commands. For example, to update and upgrade your Ubuntu installation you would type sudo apt-get update && sudo apt-get upgrade, and to create an alias for it you would only have to add something like the following inside the ~/.bashrc file:

alias update='sudo apt-get update && sudo apt-get upgrade'

Now, each time you type update, the command inside the single quotes will be executed.

Have some other tips that others may find useful? Please share them in the comments below.

Sunday, 3 May 2009

How-To: Configure Bash to Show Some Info and Greet the User When Invoked

In this tutorial I'll show how to add some message (or run whatever application, echo whatever text you wish) when you start Bash in a terminal application like GNOME Terminal or Konsole.

When Bash is started in interactive way it will execute the commands found in ~/.bashrc, where ~ is you home directory. This file usually contains the PS1 variable (which holds the way the prompt looks like (by default this is user@host in most distribution), aliases, instructions to execute the /etc/bash_completion and ~/.bash_aliases files if found etc.

In order to show some message when Bash starts we will add the commands we want executed at the end of this file, so edit it with your favourite text editor, e.g. nano ~/.bashrc and add something like this:

fortune

This command will echo some random quote from a database which has over 15.000 quotes. Notice that you will have to install the fortunes package, in example on a Debian system type as root:

apt-get install fortunes

You can add any command you want executed to ~/.bashrc, for example I have those:

echo -ne "Hello, $USER! Today is $(date).\n\n"
cal
echo -ne "System Info: $(uptime)\n\n"
echo -ne "Fortune of the Day:\n"
/usr/games/fortune

Here's a screenshot of the output for those commands:


As you can see, first it echoes a message to the currently logged in user, it shows the date, invokes the cal application which will display a calendar, it shows the system uptime and then echoes a quote using the fortune game.