Skip to content

Instantly share code, notes, and snippets.

@remyd1
Last active September 28, 2020 13:51
Show Gist options
  • Save remyd1/57f825ca6880ae74f59d to your computer and use it in GitHub Desktop.
Save remyd1/57f825ca6880ae74f59d to your computer and use it in GitHub Desktop.
equivalent of bash command "ls -lt | head -n X" (you have to source it)
# This bash function is usefull to list most recent things in a directory.
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
# . ~/bin/lt
#
lt() {
comm="ls"
opt="-lt"
if [ -n "$LT_SHOW_HIDDEN" ];then
if [ $LT_SHOW_HIDDEN -eq 1 ];then
opt=$opt"a"
fi
fi
if [ -n "$LT_REVERSE" ];then
if [ $LT_REVERSE -eq 1 ];then
opt=$opt"r"
fi
fi
num=10
usage="usage: lt [number] [directory_A] [directory_B]\nExample: 'lt 15 /var/log'\nDefault value for number is 10 (see head command)\nIf you do not want to see hidden files, set environment variable 'LT_SHOW_HIDDEN' to 1 before sourcing the lt.sh function.\nYou can also set LT_REVERSE to 1 to get the older files first."
re='^[0-9]+$'
if [ "$1" = "-h" ] || [ "$1" = "--help" ];then
echo $usage
elif [ -z "$1" ];then
echo "$comm $opt |head -$((num+1))"
$comm $opt |head -$((num+1))
elif echo $1 |grep -Eq $re; then
num=$1
if [ -z "$2" ];then
$comm $opt |head -$((num+1))
else
for dir in $@
do
shift
if [ $dir != $num ]; then
echo $dir
$comm $opt $dir |head -$((num+1))
fi
done
fi
elif [ -d $1 ]; then
# ok, user did not read the usage
echo $usage
if [ -z "$2" ];then
$comm $opt $1 |head -$((num+1))
elif echo $2 |grep -Eq $re;then
num=$2
$comm $opt $1 |head -$((num+1))
else
echo "The second arg is not a number. I will consider that other args are folders."
for dir in $@
do
echo $dir
$comm $opt $dir |head
done
fi
else
if [ -f $1 ]; then
$comm $opt $1
else
echo $usage;
echo "Are you sure that your argument is valid (existing and browsable directory/file) ?"
fi;
fi;
}
@remyd1
Copy link
Author

remyd1 commented Sep 28, 2020

compatibility with zsh for LT_SHOW_HIDDEN and LT_REVERSE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment