小编Poo*_*nam的帖子

如何抑制 bash 脚本中的错误

我试图抑制 date 命令生成的错误,但执行脚本后仍然出现错误。

#!/usr/bin/bash

input="30 FEB 2022"
reg="^[0-9]{1,2}\s[a-zA-Z]{1,3}\s[0-9]{1,4}$"

if [[ $input =~ $reg ]]
then
        echo "VALID Date Format : $input"
        #output=$(`date -d "$input" +"%d-%b-%Y, %A"` 2>&1 > /dev/null)
        output=`date -d "$input" +"%d-%b-%Y, %A"` 2>&1 > /dev/null
else
        echo "INVALID Date Format : $input"
        output="-1"
fi

echo $output
Run Code Online (Sandbox Code Playgroud)

执行后输出 -

root@ip-xx-x-xx-xxx:~# ./exDate.sh 
VALID Date Format : 30 FEB 2022
date: invalid date '30 FEB 2022'
Run Code Online (Sandbox Code Playgroud)

请告知我如何抑制错误?

shell-script regular-expression

3
推荐指数
2
解决办法
2923
查看次数

Bash:“[0-9]+$”正则表达式无法仅匹配 3 位数字

我已经执行了下面的代码来检查字段“eid”的长度是否为 3 位数字并且全部都是数字 -

#!/usr/bin/bash

input="A01#PoonamSahani#IVS#123456"

#recCount=`echo $input | awk -F "#" '{print NF}'`

eid=`echo $input | cut -d "#" -f 1`
ename=`echo $input | cut -d "#" -f 2`
dept=`echo $input | cut -d "#" -f 3`
salary=`echo $input | cut -d "#" -f 4`

if [[ ${#eid} == 3 && $eid =~ [0-9]+$ ]]
then
        echo "$eid"
else
        echo "Check"
fi
Run Code Online (Sandbox Code Playgroud)

执行后得到以下输出 -

root@ip-xx-xx-xx-xx:~# ./3ex.sh 
A01
Run Code Online (Sandbox Code Playgroud)

请告知这里缺少什么?

bash regular-expression

2
推荐指数
1
解决办法
2434
查看次数

带有 ((...)) 字符串比较的 if 语句在 bash 脚本中不起作用

我写了下面的脚本:

#!/usr/bin/bash

STR_1="nfosys"
STR_2="Infosys"

if (( $STR_1 == $STR_2 ))
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi
Run Code Online (Sandbox Code Playgroud)

获取输出:

root:~/Desktop/user_repo/Demo# bash -x test.sh 
+ STR_1=nfosys
+ STR_2=Infosys
+ ((  nfosys == Infosys  ))
+ echo 'Strings are equal'
Strings are equal
root:~/Desktop/user_repo/Demo# 
Run Code Online (Sandbox Code Playgroud)

理想情况下,它应该打印“字符串不相等”语句,但我无法理解为什么它打印“字符串相等”

bash string shell-script

1
推荐指数
1
解决办法
5322
查看次数

标签 统计

bash ×2

regular-expression ×2

shell-script ×2

string ×1