cd /tmp
if [[ $(echo "`pwd`" | awk -F '/' '{print $NF}') == "tmp" ]]; then
echo "YES"
else
echo "NO"
fi
cd -
Yes prints like this:
YES
/tmp
but I want only
YES
cd /tmp
if [[ $(echo "`pwd`" | awk -F '/' '{print $NF}') == "tmp" ]]; then
echo "YES"
else
echo "NO"
fi
cd -
Yes prints like this:
YES
/tmp
but I want only
YES
What's printing the path is the cd -
command at the end. It prints the path so that you can see what working directory you end up in. This is a special behavior of cd
when called with the operand -
(a single dash), in which case it is equivalent to
cd "$OLDPWD" && pwd
To avoid this, you could use cd "$OLDPWD"
instead (OLDPWD
is a special variable that will hold the value of the previous working directory), but notice that if cd /tmp
failed and your code outputs NO
, then both cd -
and cd "$OLDPWD"
may take you to an unexpected directory.
Instead, use
(
cd /tmp
if [[ $(echo "`pwd`" | awk -F '/' '{print $NF}') == "tmp" ]]; then
echo YES
else
echo NO
fi
)
The first cd
will not affect the working directory outside of the (...)
subshell.
Also, your test would be much more safely and efficiently performed with
if [[ $PWD == */tmp ]]; then
echo YES
else
echo NO
fi
The PWD
variable will contain the pathname of the current working directory, and is often what you want to use instead of the pwd
command. The test simply tests whether the pathname of the current working directory ends with the string /tmp
, which is what your awk
code appears to want to do as well (but would fail to do if the pathname contains newlines).
If all you want is to check whether it's possible to cd
into /tmp
, but to not actually do that, use
( if cd /tmp; then echo YES; else echo NO; fi )
On systems with an external cd
utility, like macOS and Solaris, you could use that like so:
if /usr/bin/cd /tmp; then
echo YES
else
echo NO
fi
An external cd
utility can never actually be used to change the working directory, but it can still be useful in tests like these that determines whether changing into a particular directory would be possible. See also What is the point of the `cd` external command?
If what you want to do is to test whether /tmp
exists and is a directory (or a symbolic link to a directory), then the most common way to do that is not with cd
but with a test like so:
if [ -d /tmp ]; then
echo YES
else
echo NO
fi
cd -
. – thanasisp Dec 20 '20 at 17:54[[ $(echo "`pwd`" | awk -F '/' '{print $NF}') == "tmp" ]]; then
was printing the path, but actuallycd -
was printing the it. I could have done 1>/dev/null 2>/dev/null. Still the answer's nice – Machinexa Dec 22 '20 at 02:36