方式1:$(命令)

例1:输出的文本中使用$(pwd)打印当前的路径

  1. [root@kedacom test]# pwd
  2. /opt/test
  3. [root@kedacom test]# echo "The current directory is $(pwd)"
  4. The current directory is /opt/test
  5. [root@kedacom test]# cd
  6. [root@kedacom ~]# echo "The current directory is $(pwd)"
  7. The current directory is /root

例2:创建的文件名称带上日期$(date +%Y-%m-%d-%H-%M-%S)

  1. [root@kedacom test]# date +%Y-%m-%d-%H-%M-%S
  2. 2022-01-31-15-48-50
  3. [root@kedacom test]# touch file-$(date +%Y-%m-%d-%H-%M-%S)
  4. [root@kedacom test]# ls
  5. file-2022-01-31-15-48-54
  6. [root@kedacom test]# touch file-$(date +%Y-%m-%d-%H-%M-%S)
  7. [root@kedacom test]# ls
  8. file-2022-01-31-15-48-54 file-2022-01-31-15-48-58

方式2:命令

touch file-date +%Y-%m-%d-%H-%M-%S可以实现上面touch file-$(date +%Y-%m-%d-%H-%M-%S)的功能

  1. [root@kedacom test]# ls
  2. file-2022-01-31-15-48-54 file-2022-01-31-15-48-58
  3. [root@kedacom test]# touch file-`date +%Y-%m-%d-%H-%M-%S`
  4. [root@kedacom test]# ls
  5. file-2022-01-31-15-48-54 file-2022-01-31-15-48-58 file-2022-01-31-15-57-14

强引用’’与弱引用””

只有在弱引用中才能实现命令替换,强引用中不能实现命令替换

  1. #弱引用
  2. [root@kedacom test]# echo "The current directory is $(pwd)"
  3. The current directory is /opt/test
  4. #强引用
  5. [root@kedacom test]# echo 'The current directory is $(pwd)'
  6. The current directory is $(pwd)
  7. #弱引用
  8. [root@kedacom test]# touch "file-`date +%Y-%m-%d-%H-%M-%S`"
  9. [root@kedacom test]# ls
  10. file-2022-01-31-16-05-01
  11. #强引用
  12. [root@kedacom test]# touch 'file-`date +%Y-%m-%d-%H-%M-%S`'
  13. [root@kedacom test]# ls
  14. file-`date +%Y-%m-%d-%H-%M-%S`