Shell Tips and Tricks

[problem]

  1. You want to trace program execution on Solaris?
  2. You want to perform network tracing on Solaris?
  3. Perform a text dump of a binary file – or see ascii codes, etc?
  4. Generate some random data?
  5. List directory contents in 3 columns?
  6. Loop through a list of files and perform actions on them?
  7. Check for values in vars?
  8. Detach a process without it dying.
  9. Perform arithmetic in shell.

[/problem]

[solution]

Some of the most useful Shell Tricks I’ve learned – check them out at Example – enjoy! 🙂

[/solution]

[example]

  1. System process debug (solaris) all exec/reads

    truss -xall -vall -rall -t'read' -p PID

  2. Network trace connection from hostname (solaris)

    snoop -x0 src hostname

  3. Optical dump of a file, useful for seeing control chars, etc and lines with no newline.

    od -c filename

  4. Generate 512 bytes of random data, cat -ve escapes control chars.

    dd bs=1 count=512 if=/dev/urandom | cat -ve

  5. list directory contents, display in 3 columns.

    ls | paste - - -

  6. Loop through all files and perform an action on it.

    for na in * ; do echo $na ; done

  7. Check for values in vars.

    [[ $(echo $var | grep -ic "pattern") -eq 0 ]] &

    You could also go for “-eq 1” – does contain or -ne 0 for same, etc. Plus you could use || for “or” either in place of “&&” or after this block – same as if .. then “positive” else “negative” fi.

  8. Detach a process without it dying.

    disown [%1]

    nohup command > /tmp/logfile.log 2>&1&

    If you start a process with nohop (ignore the hup signal), it will not exist (usually) when your shell is exited. This can now be simulated on solaris, by backgrounding a process (with ctrl Z and bg) then typing disown. jobs command will show all backgrounded jobs. Ideally start commands like this, to avoid the shell exit problem:

  9. Perform arithmetic in shell.

    bc -l

    Binary Calculator in long format – for float, etc. Can also be automated like this, to convert between decimal and hex:

    i=0; while ((i<20)) ; do echo -n "$i: "; echo "base=10;obase=16;$i" | bc; ((i++)); done | paste - - - -
    0: 0 1: 1 2: 2 3: 3
    4: 4 5: 5 6: 6 7: 7
    8: 8 9: 9 10: A 11: B
    12: C 13: D 14: E 15: F
    16: 10 17: 11 18: 12 19: 13

[/example]

[reference]

[tags]Unix Shell Tips, Unix Shell Tricks, UNIX Arithmetic, Optical Dump, Unix Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *