[英]Changing to newest or oldest directory — csh idiom not working in bash
Please let me know why the following command works in csh mode and not in bash. 请让我知道为什么以下命令在csh模式下而不在bash下工作。
Bash: 重击:
~ $ cd `ls -ltr | grep ^d | tail -1 | awk '{print $9}'`
bash: cd: synopsys_cache_L-2016.03-SP5: No such file or directory
~ $ pwd
/home/mkumar
after changing to csh: 更改为csh后:
~ $ csh
CSH > cd `ls -ltr | grep ^d | tail -1 | awk '{print $9}'`
CSH > pwd
/home/mkumar/synopsys_cache_L-2016.03-SP5
Code that relies on parsing ls
is innately bug-prone . 依赖于
ls
代码天生就容易出错 。 Don't do it. 不要这样
The below gets a little fancy, reusing the same code to build both cd_newest
and cd_oldest
functions: 下面的代码有点花哨,重复使用相同的代码来构建
cd_newest
和cd_oldest
函数:
cd_by_test() {
local test=$1 dir best_dir=
shift
(( "$#" == 0 )) && set -- */
for dir; do dir=${dir%/}
[[ -d "$dir" ]] || continue
[[ $best_dir ]] || best_dir=$dir
[ "$dir" "$test" "$best_dir" ] && best_dir=$dir
done
if [[ $best_dir ]]; then
cd "$best_dir"
else
echo "No directory found" >&2
fi
}
cd_newest() { cd_by_test -nt "$@"; }
cd_oldest() { cd_by_test -ot "$@"; }
Here, we're setting the operator to use two compare two files by assigning it to the variable $test
within the cd_by_test
function, and then using [ "$dir" "$test" "$best_dir" ]
to apply that operator. 在这里,我们将运算符设置为使用两个比较两个文件,方法是将其分配给
cd_by_test
函数中的变量$test
,然后使用[ "$dir" "$test" "$best_dir" ]
来应用该运算符。
In the recently-amended version, we can also pick between a specific subset of directories: 在最近修订的版本中,我们还可以在目录的特定子集之间进行选择:
cd_newest *-test.d/
...will cd
to the newest *-test.d
directory. ...将
cd
到最新的*-test.d
目录。
Unsolicited plug for zsh
(as justification, I'd suggest considering zsh
if you are just interested in moving to a shell other than csh
). 不请自来的
zsh
插件(作为理由,如果您只想迁移到csh
以外的其他外壳,我建议考虑使用zsh
)。
% cd *(/om[1])
% pwd
/home/mkumar/synopsys_cache_L-2016.03-SP5
The parentheses following *
contain various glob qualifiers : *
后面的括号包含各种glob 限定符 :
/
limits the match to directories /
将匹配项限制为目录 om
sorts the expansion by modification time om
按修改时间对扩展进行排序 [1]
selects only the first match [1]
仅选择第一个比赛
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.