shell if -n 参数的使用

参考:shell if -n 参数-CSDN博客

if [ -n str ] 当str非空的时候,为true,例:

#!/bin/bash

if [ -n $1 ];then
   echo "with args : $1"
else
   echo "without args"
fi

上面的几行脚本,不管我们是否传入参数,都是输出with args 这行,也就是结果一直为true。原因是当我们的str没有用""引起来的时候,if [ -n $1 ] 相当于if [ -n ]。

正确的用法应该是这样,用"" 把-n 后面的str括起来

#!/bin/bash

if [ -n "$1" ];then
   echo "with args : $1"
else
   echo "without args"
fi

如果我们不想写""引号,还可以把判断条件写成这样(用[[ -n $1 ]]):

#!/bin/bash

if [[ -n $1 ]];then
   echo "with args : $1"
else
   echo "without args"
fi

if的参数:
-e 选项来测试文件是否存在。
-gt 选项来测试 number 是否大于零。
-z 选项来测试字符串是否为空。
-x 选项来测试文件是否具有执行权限。
-nt 选项来测试 file1 是否比 file2 新。
参考: https://cn.linux-console.net/?p=23407

test命令参考: https://www.bookstack.cn/read/bash-tutorial/docs-condition.md

posted @ 2025-02-22 19:04  老禾的账本  阅读(841)  评论(0)    收藏  举报