`(cd X; pwd)` sometimes returns two lines

I have a shell script that starts with:

sdir=`dirname $0`
sdir=`(cd "$sdir/"; pwd)`

And it usually expands (with 'sh -h') in

++ dirname /opt/foo/bin/bar
+ sdir=/opt/foo/bin
++ cd /opt/foo/bin/
++ pwd
+ sdir=/opt/foo/bin

but for one user for one combination of parameters in the extension (note the two lines in the value of the sbin result)

++ dirname bin/foo
+ sdir=bin
++ cd bin/
++ pwd
+ sdir='/opt/foo/bin
/opt/foo/bin'

I tried different combinations, but could not reproduce this behavior. With different input parameters for this user, he began to produce the correct result of one line. I am new to shell scripts, so please advise when (cd X; pwd)can return two lines. this has been observed on CentOS, but not sure if it matters. Please advice.

+3
source share
5 answers

Criminal - cd, try instead

sdir=`dirname $0`
sdir=`(cd "$sdir/" >/dev/null; pwd)`

, , CDPATH, cd , .

man bash :

       CDPATH The  search  path  for  the  cd command.  This is a
              colon-separated list of directories  in  which  the
              shell  looks  for destination directories specified
              by the cd command.  A sample value is ``.:~:/usr''.

       cd [-L|-P] [directory]

              Change the current working directory to directory. If 
              directory is not given, the value of the HOME shell 
              variable is used. If the shell variable CDPATH exists,
              it is used as a search path. If directory begins with a slash, 
              CDPATH is not used.

              The -P option means to not follow symbolic links; symbolic 
              links are followed by default or with the -L option. If 
              directory is ‘-’, it is equivalent to $OLDPWD.

              If a non-empty directory name from CDPATH is used, or if ‘-’ 
RELEVANT  -\  is the first argument, and the directory change is successful, 
PARAGRAPH -/  the absolute pathname of the new working directory is written 
              to the standard output.

              The return status is zero if the directory is successfully 
              changed, non-zero otherwise. 

       OLDPWD The  previous  working  directory  as set by the cd
              command.

+5

CDPATH - . "unset CDPATH; CDPATH", script.

+1

, "cd". , "/usr/bin/cd" ( - "cd" ).

0

pwd "echo $PWD". , pwd , /usr/bin. " pwd" " pwd" , , .

0

:

sdir=$( cd $(dirname "$0") > /dev/null && pwd )

This is only one line and will keep all special characters in the directory name intact. Remember that on Unix, only two characters are illegal in the / dir file name: 0-byte and /(forward slash). Especially, newlines are valid in the file name!

0
source

Source: https://habr.com/ru/post/1699676/


All Articles