如何存储“ls”的结果在变量中,然后 cd 进入该变量
我想将 ls 的结果存储在一个变量中,然后我想 cd 到该变量中。
我的脚本如下。
Cd /home/dev/command
work_dir=$(ls -ltrd log$(date +%y%m%d)\* | tail -n 1)
echo $work_dir
cd “/home/dev/command/$work_dir”
它显示错误,例如没有这样的文件或目录
如何将 CD 插入 ls 命令显示的目录
I would like to store the result of ls in a variable , then I want to cd into that variable.
I have script as follows.
Cd /home/dev/command
work_dir=$(ls -ltrd log$(date +%y%m%d)\* | tail -n 1)
echo $work_dir
cd “/home/dev/command/$work_dir”
It showing error like no such file or directory
How to CD into the directory which the ls command is showing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用的是 unicode
“ U+201C
和” U+201D
左右双引号,它们用于英文文本而不是纯" U+0022
引号。因此 bash 认为引号是目录名称的一部分。You're using the unicode
“ U+201C
and” U+201D
left and right double quotation marks, which are used in english text instead of the plain" U+0022
quotation mark. So bash thinks the quotations are part of the directory name.除了 perivesta的答案,我还会提出一些要点:
CD/HOME/DEV/命令
中的命令。也许您使用的是基于Windows的环境(Cygwin或WSL?),中逃脱了
ls -ltrd log $(日期 +%y%m%d)\*,如果您的目录名称实际上以字面的星号结尾,那是正确的,但是星号通常被用作通配符,以允许替换任何数量的字符。
ls
的输出很难正确执行,如果您要求ls -l </code>输出,则更难的是
由于您似乎想要与特定模式相匹配的最新目录,因此我建议使用可以在本机上进行修改日期(例如ZSH)进行修改日期的unix shell。
更改为正确的目录后,这会要求ZSH更改为与通配符
log $(日期 +y%m%d)*
用进行修改日期(最新的)排序的目录*
(OM),使用[1]
从该列表中选择第一个(最新)项目。Besides the unicode quotation marks mentioned in perivesta's answer, I'd also make some additional points:
cd
command inCd /home/dev/command
. Perhaps you're using a Windows-based environment (cygwin or WSL?)*
inls -ltrd log$(date +%y%m%d)\*
, which would be correct if your directory names actually ended in a literal asterisk, but an asterisk is often used as a wildcard to allow the substitution of any number of characters.ls
is hard to do correctly, and even harder if you're asking forls -l
output, as Fravadona hinted at in their comment!Since you appear to want the most recent directory that matches a particular pattern, I would recommend using a UNIX shell that can sort by modification date natively, such as zsh.
After changing to the right directory, this asks zsh to change to the directory that matches the wildcard
log$(date +y%m%d)*
sorted by modification date (newest first) with(om)
, picking the first (newest) item from that list with[1]
.