Commands tagged echo (86)

  • 2
    leapyear() { [ $(date -d "Dec 31, $1" +%j) == 366 ] && echo leap || echo not leap; }
    taliver · 2010-03-30 20:13:56 2
  • One of the first functions programmers learn is how to print a line. This is my 100% bash builtin function to do it, which makes it as optimal as a function can be. The COLUMNS environment variable is also set by bash (including bash resetting its value when you resize your term) so its very efficient. I like pretty-output in my shells and have experimented with several ways to output a line the width of the screen using a minimal amount of code. This is like version 9,000 lol. This function is what I use, though when using colors or other terminal features I create separate functions that call this one, since this is the lowest level type of function. It might be better named printl(), but since I use it so much it's more optimal to have the name contain less chars (both for my programming and for the internal workings). If you do use terminal escapes this will reset to default. tput sgr0 For implementation ideas, check my Show Sample Output

    L(){ l=`builtin printf %${2:-$COLUMNS}s` && echo -e "${l// /${1:-=}}"; }
    AskApache · 2010-06-14 04:35:30 3
  • For this hack you need following function: finit() { count=$#; current=1; for i in "[email protected]" ; do echo $current $count; echo $i; current=$((current + 1)); done; } and alias: alias fnext='read cur total && echo -n "[$cur/$total] " && read' Inspired by CMake progress counters. Show Sample Output

    finit "1 2 3" 3 2 1 | while fnext i ; do echo $i; done;
    mechmind · 2010-06-17 10:20:49 0
  • Exactly the same number of characters, exactly the same results, but with bc Show Sample Output

    echo "($(date +%s)-$(date +%s -d "march 1"))/86400"|bc
    nickwe · 2010-07-22 19:44:50 0
  • This is a command template for achiving the following: * loop over files --> find -name "" | while read file; do ...; done * output progress --> echo -n . * execute some command on each file and save output for later usage --> output=$() * if command failed, open subshell and echo newline --> || (echo;...;...;) * echo output of command --> echo "$output" Show Sample Output

    find <dir> -name "<pattern>" | while read file; do echo -n .; output=$(<command>) || (echo ; echo $file:; echo "$output"; ); done
    Marco · 2010-08-10 11:45:31 1
  • While going through the source code for the well known ps command, I read about some interesting things.. Namely, that there are a bunch of different fields that ps can try and enumerate for you. These are fields I was not able to find in the man pages, documentation, only in the source. Here is a longer function that goes through each of the formats recognized by the ps on your machine, executes it, and then prompts you whether you would like to add it or not. Adding it simply adds it to an array that is then printed when you ctrl-c or at the end of the function run. This lets you save your favorite ones and then see the command to put in your .bash_profile like mine at : Note that I had to do the exec method below in order to pause with read. t () { local r l a P f=/tmp/ps c='command ps wwo pid:6,user:8,vsize:8,comm:20' IFS=' '; trap 'exec 66 exec 66 $f && command ps L | tr -s ' ' >&$f; while read -u66 l >&/dev/null; do a=${l/% */}; $c,$a k -${a//%/} -A; yn "Add $a" && P[$SECONDS]=$a; done } Show Sample Output

    for p in `ps L|cut -d' ' -f1`;do echo -e "`tput clear;read -p$p -n1 p`";ps wwo pid:6,user:8,comm:10,$p kpid -A;done
    AskApache · 2010-10-12 06:42:10 2
  • This uses some tricks I found while reading the bash man page to enumerate and display all the current environment variables, including those not listed by the 'env' command which according to the bash docs are more for internal use by BASH. The main trick is the way bash will list all environment variable names when performing expansion on ${!A*}. Then the eval builtin makes it work in a loop. I created a function for this and use it instead of env. (by aliasing env). This is the function that given any parameters lists the variables that start with it. So 'aae B' would list all env variables starting wit B. And 'aae {A..Z} {a..z}' would list all variables starting with any letter of the alphabet. And 'aae TERM' would list all variables starting with TERM. aae(){ local __a __i __z;for __a in "[email protected]";do __z=\${!${__a}*};for __i in `eval echo "${__z}"`;do echo -e "$__i: ${!__i}";done;done; } And my printenv replacement is: alias env='aae {A..Z} {a..z} "_"|sort|cat -v 2>&1 | sed "s/\\^\\[/\\\\033/g"' From: Show Sample Output

    for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv
    AskApache · 2010-10-27 07:16:54 0
  • cryptic version Show Sample Output

    read -a A <<<"8 9 5 10 6 0 3 11 7 4";B='.*.**..*....***';for C in $(date +"%H%M"|fold -w1);do echo "${B:${A[C]}:4}";done
    unefunge · 2010-11-26 11:29:23 2
  • An alternative which does not require to be root

    echo <percentage> | sudo dd of=/proc/acpi/video/VGA/LCD/brightness
    alperyilmaz · 2011-01-05 03:57:58 2
  • This is just a slight alternative that wraps all of #7917 in a function that can be executed Show Sample Output

    anagram(){ s(){ sed 's/./\n\0/g'<<<$1|sort;};cmp -s <(s $1) <(s $2)||echo -n "not ";echo anagram; }; anagram foobar farboo;
    bbbco · 2011-02-17 15:10:43 1
  • Run the alias command, then issue ps aux | tail and resize your terminal window (putty/console/hyperterm/xterm/etc) then issue the same command and you'll understand. ${LINES:-`tput lines 2>/dev/null||echo -n 12`} Insructs the shell that if LINES is not set or null to use the output from `tput lines` ( ncurses based terminal access ) to get the number of lines in your terminal. But furthermore, in case that doesn't work either, it will default to using the default of 80. The default for TAIL is to output the last 10 lines, this alias changes the default to output the last x lines instead, where x is the number of lines currently displayed on your terminal - 7. The -7 is there so that the top line displayed is the command you ran that used TAIL, ie the prompt. Depending on whether your PS1 and/or PROMPT_COMMAND output more than 1 line (mine is 3) you will want to increase from -2. So with my prompt being the following, I need -7, or - 5 if I only want to display the commandline at the top. ( ) 275MB/748MB [7995:7993 - 0:186] 06:26:49 Thu Apr 08 [[email protected]:/dev/pts/0 +1] ~ In most shells the LINES variable is created automatically at login and updated when the terminal is resized (28 linux, 23/20 others for SIGWINCH) to contain the number of vertical lines that can fit in your terminal window. Because the alias doesn't hard-code the current LINES but relys on the $LINES variable, this is a dynamic alias that will always work on a tty device. Show Sample Output

    alias tail='tail -n $((${LINES:-`tput lines 2>/dev/null||echo -n 80`} - 7))'
    AskApache · 2012-03-22 02:44:11 2
  • This command will create a popup reminder window to assist in remembering tasks is how it looks when created Show Sample Output

    echo "DISPLAY=$DISPLAY xmessage call the client" | at 10:00
    op4 · 2015-05-01 14:57:15 1
  • Print out your age in days in binary. Today's my binary birthday, I'm 2^14 days old :-) . This command does bash arithmatic $(( )) on two dates: Today: $(date +%s) Date of birth: $(date +%s -d YYYY-MM-DD) The dates are expressed as the number of seconds since the Unix epoch (Jan 1970), so we devide the difference by 86400 (seconds per day). . Finally we pipe "obase=2; DAYS-OLD" into bc to convert to binary. (obase == output base) Show Sample Output

    echo "obase=2;$((($(date +%s)-$(date +%s -d YYYY-MM-DD))/86400))" | bc
    flatcap · 2015-10-19 15:40:32 0

  • 1
    echo $((`eix --only-names -I | wc -l` * 100 / `eix --only-names | wc -l`))%
    leavittx · 2009-08-02 22:01:27 0

  • 1
    echo init 0 | at now + 2 hours
    hemanth · 2009-08-22 08:10:46 0
  • Grabs the cmdline used to execute the process, and the environment that the process is being run under. This is much different than the 'env' command, which only lists the environment for the shell. This is very useful (to me at least) to debug various processes on my server. For example, this lets me see the environment that my apache, mysqld, bind, and other server processes have. Here's a function I use: aa_ps_all () { ( cd /proc && command ps -A -opid= | xargs -I'{}' sh -c 'test $PPID -ne {}&&test -r {}/cmdline&&echo -e "\n[{}]"&&tr -s "\000" " "<{}/cmdline&&echo&&tr -s "\000\033" "\nE"<{}/environ|sort&&cat {}/limits' ); } From my .bash_profile at Show Sample Output

    cd /proc&&ps a -opid=|xargs -I+ sh -c '[[ $PPID -ne + ]]&&echo -e "\n[+]"&&tr -s "\000" " "<+/cmdline&&echo&&tr -s "\000\033" "\nE"<+/environ|sort'
    AskApache · 2010-10-22 02:34:33 3
  • I have used single packet, and in a silent mode with no display of ping stats. This is with color and UI improvement to the It is as per the enhancements suggested. Show Sample Output

    echo -n "IP Address or Machine Name: "; read IP; ping -c 1 -q $IP >/dev/null 2>&1 && echo -e "\e[00;32mOnline\e[00m" || echo -e "\e[00;31mOffline\e[00m"
    crlf · 2012-02-09 07:00:03 1
  • This is flatcaps tweaked command to make it work on SLES 11.2

    for i in /var/spool/cron/tabs/*; do echo ${i##*/}; sed 's/^/\t/' $i; echo; done
    harpo · 2012-07-12 08:07:20 1
  • eg: printTextInColorRed foo bar foo bar [in red color]

    printTextInColorRed () { echo -e '\033[01;31m\033[K'"[email protected]"'\033[m\033[K' ;} ## print text/string in color red
    totti · 2013-08-28 10:06:59 0
  • I learned a few things reading this command. But I did run into a few issues: 1. On systems that don't use GNU echo (e.g. macOS 10.14.5 Mojave), the e option may not be supported. In this case ANSI escape codes will echoed as text and the terminal will not flash, like this: \e[?5h\e[38;5;1m A L E R T Thu Jun 20 16:31:29 PDT 2019 2. Since the read command strips\ignores leading backslashes, if a user types the backslash character once in the loop, it will not break. Typing backslash twice in a loop will break as expected. 3. The foreground color is set to red (\e[38;5;1m) on every loop. This could be set once before we call while, and then reset once when the loop breaks. 4. Instead of resetting the foreground color when it breaks, the video mode is set back to normal (\e[?5l). This has the effect of leaving the terminal text red until it is manually reset. The alternative I'm proposing here addresses these issues. I tested it on macOS and Arch Linux. Show Sample Output

    printf "\e[38;5;1m"; while true; do printf "\e[?5h A L E R T %s\n" "$(date)"; sleep 0.1; printf "\e[?5l"; read -r -s -n1 -t1 && printf "\e[39m" && break; done
    z80a · 2019-06-21 00:05:16 0
  • Echos the number of seconds from the current time till the specified time (Example in command is (2**31-1)) aka the Unix epoch. Just replace that number with the specified date (in seconds past Jan. 1st 1970) and it will return the seconds. NOTE: Only works in bash Show Sample Output

    echo $( (( $( (2**31 -1) ) - $(date +%s) )) )
    Chartreuse · 2009-04-02 05:14:23 2
  • I never can remember the syntax of awk. You can give a different -d option to cut to separate by e.g. commas. Also this allows to do more things with the generated SQL, e.g. to redirect it into different files. Show Sample Output

    for each in `cut -d " " -f 1 inputfile.txt`; do echo "select * from table where id = \"$each\";"; done
    hfs · 2009-09-23 13:29:16 0
  • Nice command to create a list, you can create too with for command, but this is so faster. Show Sample Output

    seq 10 |xargs -n1 echo Printing line
    Waldirio · 2009-10-15 11:05:35 0
  • A command to find out what the day ends in. Can be edited slightly to find out what "any" output ends in. NB: I haven't tested with weird and wonderful output. Show Sample Output

    date +%A | cut -c $(( $(date +%A | wc -c) - 1 ))
    DaveQB · 2010-04-07 00:23:15 2
  • Use bc for decimals...

    echo $(echo 'scale=2; ' '100 * ' $(eix --only-names -I | wc -l) / $(eix --only-names | wc -l) | bc -l)%
    MeaCulpa · 2010-10-25 15:42:15 0
  •  < 1 2 3 4 > 

What's this? 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

Show Apt/Dpkg configuration
Shows all configurations to apt and dpkg, rarely changed, you probably still have the default configuration. Go ahead and explore your configuration if you dare, perhaps change your apt-cache directory, Dir::Cache "var/cache/apt/"; or the names of the log files.

This is regarding the command 8263 using an alias to fill in command line options for psql. You can actually just type 'psql'. In order for that to work, you want to set environment variables PGDATABASE, PGHOST, PGUSER, and (except you're using the default) PGPORT. Also, you can add a line "host:port:dbname:user:password" (asterisk ok in some columns) to your ~/.pgpass file. Finally, if you don't like the aligned columns, you can add the line "\pset format unaligned" to your ~/.psqlrc file.

Count items in JSON array
Pipe any JSON to jq, then count with the appropiate expression and use the | length on the array

List files with full path
Prints contents of current directory with the full path prepended to each entry. You can add '-type f' if you don't want the directories to show up (for those less familiar with find). I can't believe ls doesn't have an option for this.

Get AWS temporary credentials ready to export based on a MFA virtual appliance
You might want to secure your AWS operations requiring to use a MFA token. But then to use API or tools, you need to pass credentials generated with a MFA token. This commands asks you for the MFA code and retrieves these credentials using AWS Cli. To print the exports, you can use: `awk '{ print "export AWS_ACCESS_KEY_ID=\"" $1 "\"\n" "export AWS_SECRET_ACCESS_KEY=\"" $2 "\"\n" "export AWS_SESSION_TOKEN=\"" $3 "\"" }'` You must adapt the command line to include: * $MFA_IDis ARN of the virtual MFA or serial number of the physical one * TTL for the credentials

Block known dirty hosts from reaching your machine
Blacklisted is a compiled list of all known dirty hosts (botnets, spammers, bruteforcers, etc.) which is updated on an hourly basis. This command will get the list and create the rules for you, if you want them automatically blocked, append |sh to the end of the command line. It's a more practical solution to block all and allow in specifics however, there are many who don't or can't do this which is where this script will come in handy. For those using ipfw, a quick fix would be {print "add deny ip from "$1" to any}. Posted in the sample output are the top two entries. Be advised the blacklisted file itself filters out RFC1918 addresses (10.x.x.x, 172.16-31.x.x, 192.168.x.x) however, it is advisable you check/parse the list before you implement the rules

diff current vi buffer edits against original file

Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy)
Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale.

[vim] Clear a file in three characters (plus enter)
% selects every line in the file. 'd' deletes what's selected. It's a pretty simple combination.

tcpdump from src to dst
then open with wireshark

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.


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: