Home > front end >  Change Permission to file with bash script
Change Permission to file with bash script

Time:12-22

I'm new with bash scripting. Why this bash script isn't working?

!/bin/bash

FILE_PATH=~/myFile.txt

function list()
{
    ls -l $FILE_PATH
}

function mod1()
{
    if [ ! -r $FILE_PATH ]; then
        chmod g r $FILE_PATH
    else
        echo "File is already readable!"
    fi

}

function mod2()
{
    if [ -r $FILE_PATH ]; then
        chmod g-r $FILE_PATH
    else
        echo "File is not readable!"
    fi
}

function changePermissions()
{
    if [ "$1" = "g r" ]; then
        mod1
    elif [ "$1" = "g-r" ]; then
        mod2
    fi
}

function result()
{
    list
    echo "Change Permission:"
    changePermissions
    list

}

result

I guess that error in if...else statement (function changePermissions). When I input g r or g-r in console after ./nameScript.sh, permission not changing.

CodePudding user response:

$1 changes the meaning for each function. To keep $1 the same meaning you need to keep passing it down, i.e.

result()
{
    list
    echo "Change Permission:"
    changePermissions $1 # pass result argument as changePermissions argument
    list
}

result $1 # pass script argument into result argument

Also, the function keyword is not required, so, I removed it.

  •  Tags:  
  • bash
  • Related