unix - `(cd X; pwd)` 有时返回两行

标签 unix shell

我的 shell 脚本以:

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

这通常会扩展(使用'sh -h')到

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

但对于单个用户,参数的单个组合扩展为(注意结果 sbin 值处的两行)

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

我尝试了不同的组合,但无法重现此行为。使用该用户的不同输入参数,它开始生成正确的单行结果。我是 shell 脚本的新手,所以当 (cd X; pwd) 可以返回两行时请指教。 它在 CentOS 上被观察到,但不确定它是否重要。请指教。

最佳答案

罪魁祸首是 cd,改用这个试试

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.

关于unix - `(cd X; pwd)` 有时返回两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/296519/

相关文章:

bash - 在不排序的情况下删除变量上的重复项

c - 如何更换系统功能?

php - 使用 php 使用 sudo 执行命令

bash - 如何使用 Bash 将一个目录合并到另一个目录?

bash - 源 shell 脚本到 makefile

linux - 在 bash 中读取时转义规则

Bash 时间格式 HH :MM in 12 hour format AM/PM

sorting - 如何排序忽略空行

linux - "top"在shell中会调用哪个系统调用?

java - 如何在 java 中运行 sh 命令并分配选项