Commands tagged bash (821)

  • In Bash, when defining an alias, one usually loses the completion related to the function used in that alias (that completion is usually defined in /etc/bash_completion using the complete builtin). It's easy to reuse the work done for that completion in order to have smart completion for our alias. That's what is done by this command line (that's only an example but it may be very easy to reuse). Note 1 : You can use given command line in a loop "for old in apt-get apt-cache" if you want to define aliases like that for many commands. Note 2 : You can put the output of the command directly in your .bashrc file (after the ". /etc/bash_completion") to always have the alias and its completion Show Sample Output


    4
    old='apt-get'; new="su-${old}"; command="sudo ${old}"; alias "${new}=${command}"; $( complete | sed -n "s/${old}$/${new}/p" ); alias ${new}; complete -p ${new}
    Josay · 2009-08-10 00:15:05 4
  • The coolest way I've found to backup a wordpress mysql database using encryption, and using local variables created directly from the wp-config.php file so that you don't have to type them- which would allow someone sniffing your terminal or viewing your shell history to see your info. I use a variation of this for my servers that have hundreds of wordpress installs and databases by using a find command for the wp-config.php file and passing that through xargs to my function. Show Sample Output


    4
    eval $(sed -n "s/^d[^D]*DB_\([NUPH]\)[ASO].*',[^']*'\([^']*\)'.*/_\1='\2'/p" wp-config.php) && mysqldump --opt --add-drop-table -u$_U -p$_P -h$_H $_N | gpg -er AskApache >`date +%m%d%y-%H%M.$_N.sqls`
    AskApache · 2009-08-18 07:03:08 7
  • works on all unices. Show Sample Output


    4
    function nowrap { export COLS=`tput cols` ; cut -c-$COLS ; unset COLS ; }
    mobidyc · 2009-09-11 15:07:00 13
  • I usually have 5 or more ssh connections to various servers, and putting this command in my .bash_profile file makes my putty window or x terminal window title change to this easily recognizable and descriptive text. Includes the username, group, server hostname, where I am connecting from (for SSH tunneling), which device pts, current server load, and how many processes are running. You can also use this for your PROMPT_COMMAND variable, which updates the window title to the current values each time you exec a command. I prefix running this in my .bash_profile with [[ ! -z "$SSH_TTY" ]] && which makes sure it only does this when connecting via SSH with a TTY. Here's some rougher examples from http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html # If set, the value is executed as a command prior to issuing each primary prompt. #H=$((hostname || uname -n) 2>/dev/null | sed 1q);W=$(whoami) #export PROMPT_COMMAND='echo -ne "\033]0;${W}@${H}:${PWD/#$HOME/~} ${SSH_TTY/\/dev\//} [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"`]\007"' #PROMPT_COMMAND='echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n 2>/dev/null|sed 1q` `command who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `command ps aux|wc -l`]\007"' #[[ -z "$SSH_TTY" ]] || export PROMPT_COMMAND #[[ -z "$SSH_TTY" ]] && [[ -f /dev/stdout ]] && SSH_TTY=/dev/stdout And here's a simple function example for setting the title: function set_window_title(){ echo -e "\033]0; ${1:-$USER@$HOST - $SHLVL} \007"; } Show Sample Output


    4
    echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n|sed 1q` `who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `ps aux|wc -l`]\007"
    AskApache · 2009-09-19 06:57:53 4
  • This corrects duplicate output from the previous command. Show Sample Output


    4
    netstat -lantp | grep -i establ | awk -F/ '{print $2}' | sort | uniq
    HarimaKenji · 2009-09-19 14:42:31 7
  • Get your server's fingerprints to give to users to verify when they ssh in. Publickey locations may vary by distro. Fingerprints should be provided out-of-band. Show Sample Output


    4
    ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub && ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub
    Mikelifeguard · 2009-10-26 17:52:41 4
  • Usage: mydir=/very/long/path/to/a/dir cd mydir I often need to cd where no man wants to go (i.e. long path). by enabling the shell option cdable_vars, I can tell cd to assume the destination is the name of a variable.


    4
    shopt -s cdable_vars
    haivu · 2009-10-26 22:10:56 5
  • An easy function to get a process tree listing (very detailed) for all the processes of any gived user. This function is also in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    4
    psu(){ command ps -Hcl -F S f -u ${1:-$USER}; }
    AskApache · 2009-11-13 06:10:33 4
  • Convert some decimal numbers to binary numbers. You could also build a general base-converter: function convBase { echo "ibase=$1; obase=$2; $3" | bc; } then you could write function decToBun { convBase 10 2 $1; } Show Sample Output


    4
    function decToBin { echo "ibase=10; obase=2; $1" | bc; }
    woxidu · 2009-11-24 22:57:58 3
  • (Apparently it is too long so I put it in sample output, I hope that is OK.) Run the long command (or put it in your .bashrc) in sample output then run: fbemailscraper YourFBEmail Password Voila! Your contacts' emails will appear. Facebook seems to have gotten rid of the picture encoding of emails and replaced it with a text based version making it easy to scrape! Needs curl to run and it was made pretty quickly so there might be bugs. Show Sample Output


    4
    fbemailscraper YourFBEmail Password
    dabom · 2010-01-31 00:44:35 45
  • Turn shell tracing and verbosity (set -xv) on/off in any Bourne-type shell If either -x or -v is set, the function turns them both off. If neither is on, both are turned on.


    4
    xv() { case $- in *[xv]*) set +xv;; *) set -xv ;; esac }
    cfajohnson · 2010-02-14 20:57:29 3

  • 4
    tail -n2000 /var/www/domains/*/*/logs/access_log | awk '{print $1}' | sort | uniq -c | sort -n | awk '{ if ($1 > 20)print $1,$2}'
    allrightname · 2010-05-10 19:08:37 3

  • 4
    awk '{print $1}' < three-column.txt > first-column.txt
    infinull · 2010-07-09 04:00:05 5
  • There is a common command for outputting a field or list of fields from each line in a file. Why wouldn't you just use cut?


    4
    cut -f 1 three-column.txt > first-column.txt
    postrational · 2010-07-11 10:13:45 5
  • works with fractions like 1/3.5


    4
    awk "BEGIN{ print $* }"
    maelcum · 2010-10-07 16:13:41 7
  • Pressing Ctrl combined with 'a' will move the cursor to the beginning of the command under bash (other shells?). I used to do this after arrowing up for the last command, then typing 'sudo ' to run the last command as root, but of course the all time greatest command here `sudo !!` is more succinct. Still Ctrl+A can be very useful when you want to edit something at/close to the beginning of the command line.


    4
    Ctrl+a
    jemptymethod · 2010-10-11 16:02:57 13
  • When debugging an ssh connection either to optimize your settings ie compression, ciphers, or more commonly for debugging an issue connecting, this alias comes in real handy as it's not easy to remember the '-o LogLevel=DEBUG3' argument, which adds a boost of debugging info not available with -vvv alone. Especially useful are the FD info, and the setup negotiation to create a cleaner, faster connection. Show Sample Output


    4
    alias sshv='ssh -vvv -o LogLevel=DEBUG3'
    AskApache · 2010-10-30 11:23:52 4
  • Turn your terminal into digital clock. Show Sample Output


    4
    while [[ 1 ]] ; do clear; banner `date +%H:%M:%S` ; sleep 1; done
    lkj · 2011-03-24 16:41:09 5
  • Obviously the example given is necessarily simple, but this command not only saves time on the command line (saves you using "cd -" or, worse, having to type a fully qualified path if your command cd's more than once), but is vital in scripts, where I've found the behaviour of "cd -" to be a little broken at times. Show Sample Output


    4
    ( cd $DIR; command; )
    sanmiguel · 2011-03-29 13:16:00 7
  • This one-liner greps first 30 direct URLs for .torrent files matching your search querry, ordered by number of seeds (descending; determined by the second number after your querry, in this case 7; for other options just check the site via your favorite web-browser). You don't have to care about grepping the torrent names as well, because they are already included in the .torrent URL (except for spaces and some other characters replaced by underscores, but still human-readable). Be sure to have some http://isup.me/ macro handy (someone often kicks the ethernet cables out of their servers ;) ). I've also coded a more user-friendly ash (should be BASH compatible) script, which also lists the total size of download and number of seeds/peers (available at http://saironiq.blogspot.com/2011/04/my-shell-scripts-4-thepiratebayorg.html - may need some tweaking, as it was written for a router running OpenWrt and transmission). Happy downloading!


    4
    wget -U Mozilla -qO - "http://thepiratebay.org/search/your_querry_here/0/7/0" | grep -o 'http\:\/\/torrents\.thepiratebay\.org\/.*\.torrent'
    sairon · 2011-04-15 15:01:16 30
  • It's quite easy to capture the output of a command and assign it in a shell's variable: day=$(date +%d) month=$(date +%m) But, what if we want to perform the same task with just one program invocation? Here comes the power of eval! date(1) outputs a string like "day=29; month=07; year=11" (notice the semicolons I added on purpose at date's custom output) which is a legal shell line. This like is then parsed and executed by the shell once again with the help of eval. Just setting 3 variables! Inspired by LinuxJournal's column "Dave Taylor's Work the Shell". Show Sample Output


    4
    eval $(date +"day=%d; month=%m; year=%y")
    xakon · 2011-07-29 12:47:26 19
  • usage: tpb searchterm example: tpb the matrix trilogy This searches for torrents from thepiratebay and displays the top results in reverse order, so the 1st result is at the bottom instead of the top -- which is better for command line users


    4
    tpb() { wget -U Mozilla -qO - $(echo "http://thepiratebay.org/search/$@/0/7/0" | sed 's/ /\%20/g') | grep -o 'http\:\/\/torrents\.thepiratebay\.org\/.*\.torrent' | tac; }
    Bonster · 2011-10-26 12:15:55 27
  • Use the standard calculator bc to convert decimals to hex Show Sample Output


    4
    hex() { bc <<< "obase=16; $1"; }
    bjomape · 2011-12-09 13:57:05 11
  • Shows the path if the module is installed or exit quietly (to simply avoid the 'No documentation found' msg). Show Sample Output


    4
    perldoc -l Module::Name 2>/dev/null
    MarxBro · 2013-01-11 23:28:13 9
  • this bash command sets it so that when you type "screen ", it searches your running screens, and present valid auto-complete choices. The output is . Note: You must have programmable completion enabled. Check with "shopt progcomp", set with "shopt -s progcomp" Show Sample Output


    4
    complete -C "perl -e '@w=split(/ /,\$ENV{COMP_LINE},-1);\$w=pop(@w);for(qx(screen -ls)){print qq/\$1\n/ if (/^\s*\$w/&&/(\d+\.\w+)/||/\d+\.(\$w\w*)/)}'" screen
    hubt · 2013-04-10 17:17:33 6
  • ‹ First  < 6 7 8 9 10 >  Last ›

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands


Check These Out

Happy Days
AFAIR this is the wording ;)

du command without showing other mounted file systems

Convert seconds to [DD:][HH:]MM:SS
Converts any number of seconds into days, hours, minutes and seconds. sec2dhms() { declare -i SS="$1" D=$(( SS / 86400 )) H=$(( SS % 86400 / 3600 )) M=$(( SS % 3600 / 60 )) S=$(( SS % 60 )) [ "$D" -gt 0 ] && echo -n "${D}:" [ "$H" -gt 0 ] && printf "%02g:" "$H" printf "%02g:%02g\n" "$M" "$S" }

Visit wikileaks.com
Who needs a DNS server

resume other user's screen session via su, without pty error
Normally, if you su to another user from root and try to resume that other user's screen session, you will get an error like "Cannot open your terminal '/dev/pts/0' - please check." This is because the other user doesn't have permission for root's pty. You can get around this by running a "script" session as the new user, before trying to resume the screen session. Note you will have to execute each of the three commands separately, not all on the same line as shown here. Credit: I found this at http://www.hjackson.org/blog/archives/2008/11/29/cannot-open-your-terminal-dev-pts-please-check.

Download SSL server certificate with opsnessl
Useful when we need to create new certificate for site when current one is near expiry. This downloaded cert can be used to provide organisational data directly to new cert. using below command. e.g. openssl x509 -x509toreq -in /tmp/example.com.cert -out example.com.csr -signkey example.com-key.pem

ssh to machine behind shared NAT
Useful to get network access to a machine behind shared IP NAT. Assumes you have an accessible jump host and physical console or drac/ilo/lom etc access to run the command. Run the command on the host behind NAT then ssh connect to your jump host on port 2222. That connection to the jump host will be forwarded to the hidden machine. Note: Some older versions of ssh do not acknowledge the bind address (0.0.0.0 in the example) and will only listen on the loopback address.

Get your external IP address without curl
Curl is not installed by default on many common distros anymore. wget always is :) $ wget -qO- ifconfig.me/ip

Null a file with sudo

power off system in X hours form the current time, here X=2


Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: