简体   繁体   中英

“Permission Denied” ls error in bash script

#!/bin/bash
#ls /home/"$(whoami)"
#ls /home/"$(whoami)/.bashrc"

[[ $# -eq 0 ]] && echo "Pass at least a valid filepath!" && exit 1;
[[ $# -eq 1 ]] && mode=1; arg1="$1"
[[ $# -eq 2 ]] && mode=2; arg1="$1"; arg2="$2"
if [[ mode -eq 1 ]]
then
while :
do
"$(ls "$1")"
[[ $? -eq 0 ]] && echo "$1 has been downloaded! I'm going to poweroff now.."
sleep 20m;
done
elif [[ mode -eq 2 ]]
then
while :
do
"$(ls "$1")" 3> /dev/null
if [[ $? -eq 0 ]]
    then
    "$(ls "$2")" 3> /dev/null
    if [[ $? -eq 0 ]]
        then
        echo "$1 \n and \n $2 \have been downloaded! I'm going to poweroff now.."
    fi
sleep 20m;
fi
done
else
echo "Not more than two arguments! Exiting.."; exit 1;

Here's my code.(it's not the final version, just testing) Given an existent filepath it returns an ls permission error. I checked the permission and tried different cases, As shown by the initial comments I checked also who's running the script(maybe it was an absurd bug(?)). I tried the same command and filepath in the bash prompt and it works perfectly. Does someone know what could be the issue? Example of error:

Documents/CheckFilesThenDo.sh: line 12: /home/user/Downloads/file: Permission denied

EDIT: As already said, it's not that the user can't ls file(real permission error). Now it seems that the "$(ls)" it's causing this behaviour(ls works). I still don't understand why.

Each Linux file has permission set to it. You can read about permissions type and... at here !

The first command in your loop,

"$(ls "$1")"

does not make much sense. You are performing a ls , collect its stdout, and interpret this information as a command to be executed.

This leaves two possibilities:

If $1 at this point contains a filename, and ls has permission to access its directory, the command will simply output this filename, and you are going to execute it. This works only if the file has execute permission, and in this case, you could have simpler written

"$1"

If $1 does not have the x-bit set, you get a "permission denied".

If however the file does not exist, ls writes nothing to stdout. You just see an error message about the missing file, but nothing is executed.

Aside from this: If you really quoted the full error message in your question, this means that the script is not executed by bash, because bash would say something like:

bash : Documents/CheckFilesThenDo.sh: : line 12: .... permission denied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM