在下面的脚本中,将文件分配给名为“ byteNuevo”的变量后,我得到文件的大小(以字节为单位)。然后进行比较,如果将'byteAnterior'> 0减去'byteNuevo-byteAnterior',否则将值分配为0。

问题是'byteAnterior'没有值,如果您在'my_text.txt'之前具有该值,希望我解释说此脚本所做的是显示它在'my_text.txt'之前具有的值,并且现在已经存在...

我的例子:

    echo -e "\n- Starting 1.sh script--\n"

if [[ ! -f my_text.txt ]]; then > my_text.txt; fi

byteOLD="$(cat somefile.storing.byteOLD.value.txt)"
echo "-- OK: so far byteOLD is: $byteOLD";

byteModified=$(stat -c'%s' my_text.txt)

echo "-- Now after modifying my_text.txt on the fly, bytes in variable byteModified are: $byteModified";

((byteDiferencia = (byteOLD > 0) ? byteModified - byteOLD : 0))
echo "  -- byteDiferencia is set to = '$byteDiferencia'"

最佳答案

看看是否有帮助?

情况1-我正在检查byteAnterior永远不会小于0-否则我将错误提示。

[jenkins@giga_akssb12 tomcat]$ cat 1.sh ; cat my_text.txt; ./1.sh ;
#!/bin/bash

echo -e "\n- Starting 1.sh script--\n"
#As you didn't mention how u r setting byteAnterior, im assuming user will pass a parameter to this script.
byteAnterior="$1"
if [[ $byteAnterior -lt 0 || -z "$byteAnterior" ]]; then echo -e "\n   -- Pass parameter value >= 0.\n"; exit 111; fi

byteNuevo=$(stat -c'%s' my_text.txt)
echo "-- byteAnterior : $byteAnterior"
echo "-- byteNuevo    : $byteNuevo"
echo

#Ternary operator use
((byteDiferencia = (byteAnterior > 0) ? byteNuevo - byteAnterior : 0))

echo "  -- byteDiferencia is set to = '$byteDiferencia'"
Hi shenzi.

ed?

- Starting 1.sh script--


   -- Pass parameter value >= 0.

[jenkins@giga_akssb12 tomcat]$
[jenkins@giga_akssb12 tomcat]$ ./1.sh 0;
- Starting 1.sh script--

-- byteAnterior : 0
-- byteNuevo    : 16

  -- byteDiferencia is set to = '0'
[jenkins@giga_akssb12 tomcat]$
[jenkins@giga_akssb12 tomcat]$
[jenkins@giga_akssb12 tomcat]$ ./1.sh 12;
- Starting 1.sh script--

-- byteAnterior : 12
-- byteNuevo    : 16

  -- byteDiferencia is set to = '4'
[jenkins@giga_akssb12 tomcat]$


情况2。如果要将byteAnterior设置为0或小于0的值,或者将有效数字以外的任何值设置为> =1。则注释掉校验(if语句),然后通过三元运算符将byteDifferntia设置为0。运行1.sh并将-1作为第一个参数传递,您将看到:

#!/bin/bash

echo -e "\n- Starting 1.sh script--\n"
#As you didn't mention how u r setting byteAnterior, im assuming user will pass a parameter to this script.
byteAnterior="$1"
#if [[ $byteAnterior -lt 0 || -z "$byteAnterior" ]]; then echo -e "\n   -- Pass parameter value >= 0.\n"; exit 111; fi

byteNuevo=$(stat -c'%s' my_text.txt)
echo "-- byteAnterior : $byteAnterior"
echo "-- byteNuevo    : $byteNuevo"
echo

#Ternary operator use
((byteDiferencia = (byteAnterior > 0) ? byteNuevo - byteAnterior : 0))

echo "  -- byteDiferencia is set to = '$byteDiferencia'"
Hi shenzi.

ed?

- Starting 1.sh script--

-- byteAnterior : -1
-- byteNuevo    : 16

  -- byteDiferencia is set to = '0'

关于linux - Shell类型 session 中的变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24190440/

10-09 20:07