Pregunta

I have a test coming up, and this is one of the questions on the study guide, but I'm not sure which is the correct answer. I believe the answer is the 4th choice. Can someone confirm this?

Consider the following Bash script. Which of the following statements is true?

#!/bin/bash
echo "ls" > newscript.sh
for i in {1..6}
do
    let REM=($i % 2)
    chmod -x newscript.sh
    if [ $REM -eq 0 ]
    then             
chmod +x newscript.sh
    fi
done
./newscript.sh

Select one:

newscript.sh will not run because the execution bit is not set

newscript.sh will run but produce no output

newscript.sh will run because the execution bit is set

newscript.sh will run but will produce an error

newscript.sh will not run because it is not a valid script

¿Fue útil?

Solución

newscript.sh will run because the execution bit is set.

How do I know? Because I tried it out.

Let's look at the iterations (1 - 6 INCLUSIVE)

i = 1. 1 % 2 = 1: Will not be executable
i = 2. 2 % 2 = 0: Will be executable
i = 3. 3 % 2 = 1: Will not be executable
i = 4. 4 % 2 = 0: Will be executable
i = 5. 5 % 2 = 1: Will not be executable
i = 6. 6 % 2 = 0: Will be executable

The percent sign is the modulus operator (ie. A % B: Think of it as the remainder of A divided by B)

So at the end if it all, the script will be executable. If you have access to a Linux machine, try it for your self and add some debug statements to trace it.

Otros consejos

for example, save the file to a.sh, and run it with this command

bash -x a.sh

You should see this output as below:

$ bash -x a.sh
+ echo ls
+ for i in '{1..6}'
+ let 'REM=(1 % 2)'
+ chmod -x newscript.sh
+ '[' 1 -eq 0 ']'
+ for i in '{1..6}'
+ let 'REM=(2 % 2)'
+ chmod -x newscript.sh
+ '[' 0 -eq 0 ']'
+ chmod +x newscript.sh
+ for i in '{1..6}'
+ let 'REM=(3 % 2)'
+ chmod -x newscript.sh
+ '[' 1 -eq 0 ']'
+ for i in '{1..6}'
+ let 'REM=(4 % 2)'
+ chmod -x newscript.sh
+ '[' 0 -eq 0 ']'
+ chmod +x newscript.sh
+ for i in '{1..6}'
+ let 'REM=(5 % 2)'
+ chmod -x newscript.sh
+ '[' 1 -eq 0 ']'
+ for i in '{1..6}'
+ let 'REM=(6 % 2)'
+ chmod -x newscript.sh
+ '[' 0 -eq 0 ']'
+ chmod +x newscript.sh
+ ./newscript.sh

it clearly shows the last chmod is +x, so the script will run because the execution bit is set.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top