0

EDIT : As @Biffen 's suggestion, putting ${SCRIPTS[*]} =~ ${ARG} in double bracket is did the trick.

E.G. if [[ ${SCRIPTS[*]} =~ ${ARG} ]]; then

I am trying to get process names as array and check given file name is if exists in that array.

When I try to run script, it throws an error on if [ ${SCRIPTS[*]} =~ ${ARG} ]; then line. I can't why I am getting this error.

#!/usr/bin/env bash

SCRIPTS=(`ps x | grep python | grep -v ".pyc" | grep -v grep | awk  '{print $NF}'`)
ARGS="$@"

kill_funct () {
    if [ !-z "$1" ]; then
        # kill -9 "$1"
        echo "$1 is killed."
    fi
}

killall_funct () {
    for SCRIPT in SCRIPTS
        do
            # kill -9 ${SCRIPT}
            echo "${SCRIPT} is killed."
        done
}

for ARG in ${ARGS}
do
    if [ -z ${ARG} ]; then
        echo "No file name or key given as parameter."
        echo "For help please use -h key."
    elif [ ${ARG} = "-h" ]; then
        echo "USAGE:"
        echo "   -h          : Displays this help"
        echo "   \"file name\" : Kills the process of the given file names"
        echo "                 You can give more than one file name as argument"
        echo "                 E.G. bash oldur.sh \"file1 name\" \"file2 name\" ..."
        echo "   All         : This parameter kills all python processes found with 'ps' command"
    elif [ ${ARG} = "All" ]; then
        killall_funct
    else
        echo ${SCRIPTS}
        if [ ${SCRIPTS[*]} =~ ${ARG} ]; then
            kill_funct ${ARG}
        else
            echo "${ARG} not present as a process."
        fi
    fi
done
Sencer H.
  • 972
  • 8
  • 29
  • `set -x` to see to what your variables expand. It's probably a quoting issue. http://www.shellcheck.net could tell you more. – Biffen Feb 02 '16 at 12:42
  • I typed `set -x` in command line and run script again but nothing changed. Output is still same. – Sencer H. Feb 02 '16 at 12:45
  • `set -x` goes in the script. Or run `bash -x – Biffen Feb 02 '16 at 12:45
  • Ok thas worked, here is the results: https://jpst.it/Fe3K – Sencer H. Feb 02 '16 at 12:48
  • 1
    *As you can see*, `[ ${SCRIPTS[*]} =~ ${ARG} ]` expands to `'[' /usr/bin/classicmenu-indicator /opt/extras.ubuntu.com/my-weather-indicator/bin/my-weather-indicator /usr/bin/terminator '=~' asdfasdfasdf ']'`, which is indeed too many arguments to `[`. What do you want that line to do? – Biffen Feb 02 '16 at 12:49
  • I want to check if given argument exists in the array. Should I reverse `[ ${SCRIPTS[*]} =~ ${ARG} ]` as `[${ARG} =~ ${SCRIPTS[*]} ]` ? – Sencer H. Feb 02 '16 at 12:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/102357/discussion-between-biffen-and-sencer-h). – Biffen Feb 02 '16 at 12:50

0 Answers0