Only if in "/" : alias ls='ls -I test'?
ls () {
case "$PWD" in
/) command ls -I test "$@" ;;
*) command ls "$@" ;;
esac
}
The above shell function will test the current directory against /
and executes the GNU ls
command differently according to the outcome of the test.
"$@"
will be replaced by the command line options and operands on the original command line.
We need to use command ls
rather than just ls
in the function to bypass the shell function lookup for ls
(which would otherwise give us a nice infinite recursion).
Note that this will not use the ignore pattern if doing ls /
from somewhere else, and that it will use the ignore pattern if doing, e.g., ls /home/dvoo
from /
.
To make it easier to remember what this actually does (six months down the line when you wonder what it's doing), use the long options:
ls () {
case "$PWD" in
/) command ls --ignore='test' "$@" ;;
*) command ls "$@" ;;
esac
}
Alternative implementation of the above function that will only call ls
from one place (and which is shorter):
ls () {
[ "$PWD" = "/" ] && set -- --ignore='test' "$@"
command ls "$@"
}
Use a function that tests if you're in /
for ls
:
ls () {
if [[ "$PWD" == / ]]
then
command ls -I test "$@"
else
command ls "$@"
fi
}
This way, any arguments you pass to ls
will still be used.
Or:
ls () {
if [ "$PWD" == / ]
then
set -- -I test "$@"
fi
command ls "$@"
}
Something like this i thought it would work:
alias ls='[[ "$PWD" = "/" ]] && ls -I test ||ls'
$PWD
is the current working directory
&&
has the action to perform if pwd is /
(condition check =true)
||
has the action to perform if pwd is not /
(condition check=false)
But after carefull testing above solution IS NOT WORKING correctly.
On the other hand this will work ok as alternative to functions:
alias ls='{ [[ "$PWD" == "/" ]] && a="-I tmp2" ||a=""; };ls $a '
Or even better, similar to other answers but without the need of function:
alias lstest='{ [[ "$PWD" == "/" ]] && set -- "-I" "tmp2" || set --; }; ls "$@"'
Possible extra flags and/or full paths given in command line when invoking this alias are preserved and sent to ls.