0
点赞
收藏
分享

微信扫一扫

如何将 Bash 命令的输出赋值给 Bash 变量

编程练习生J 2022-04-29 阅读 180
bash

有时需要将 Bash 命令的输出保存以作他用。Bash 提供了两种将 Bash 命令的输出赋值给 Bash 变量的方法。

方法一:

variable=$(command)
variable=$(command [option…] argument1 arguments2 …)
variable=$(/path/to/command)

方法二:

variable=`command`
variable=`command [option…] argument1 arguments2 …`
variable=`/path/to/command`

举个例子:将日期赋值给 Bash 本地变量:

[11:49:27]$ curr_date=$(date)

[11:50:17]$ date && echo $curr_date
2022年 4月28日 星期四 11时50分55秒 CST
2022年 4月28日 星期四 11时50分17秒 CST

另一个例子:用 vim 阅读长文本时,可以把当前阅读的行数写到末行;下次可以用下面的命令继续阅读。

vim +$(tail -n 1 test.txt) test.txt
举报

相关推荐

0 条评论