More Useful Linux Examples

Continuing from my first “Useful-Linux-Examples” post , yet another eclectic collection of useful things in Linux

I need to delete some old files

find /path/to/directory/ -name '*.log' -type f -mtime +7 -delete

Important flags:

  • “Dryrun”: -depth -print
  • -mtime [<-/+>]<days> filter lasted modified, NB! the number sign of the number is important and a little unintuitive… e.g.
    • -mtime 7 -> less than 7 days ago
    • -mtime -7 -> same as above
    • -mtime +7 -> more than 7 days ago
  • -type f filter for only files
  • -mindepth 1 if not filtering for files only (-type f), can be used to not delete the directory you are searching, if it matches the name
  • -maxdepth 10 directory depth
  • -not <other filter> to negate the following filter
  • -iname case insensitive version of -name

NB: The filters apply from left to right, so make sure -delete goes last

What ports are in use?

sudo netstat -tulpn | grep LISTEN

Git

I often find myself needing to make small modification to commits in my current feature branch, which I don’t need to be a separate commit. E.g. re-formatting, or bugfixes in whatever I just implemented. Using --fixup is a quick way to refine an earlier commit

git commit [-a] --fixup=<commit to squash into>
# e.g. more often than not
git commit -a --fixup=HEAD

Which I can then clean up as so (before raising a merge/pull request)

git rebase -i HEAD~<some number of commits> --autosquash

Need to know how many commit are in your branch? See here

Inline files / multiline strings aka Heredoc

With variables templated (although manual escaping is possible):

MY_VAR=ABC
cat << EOF
<Contents of file $MY_VAR>
EOF

outputs

<Contents of file ABC>

Or, exactly as is, no need to worry about escaping

MY_VAR=ABC
cat << 'EOF'
<Contents of file $MY_VAR>
EOF

would output

<Contents of file $MY_VAR>

This can be useful for writing files from a script

cat << 'EOF' > /path/to/file
<Contents of file>
EOF

You can use different delimiters if you need to nest heredocs

cat << 'EOF_OUTER' > /path/to/outer_file

cat << 'EOF' > /path/to/file
<Contents of inner file>
EOF

EOF_OUTER

Useful packages / commands

  • Augeas - For when sed isn’t simple to use to edit the config file
  • strace - Understanding exactly what something is doing

Continues here: “Even-More-Useful-Linux-Examples”