how to execute kubectl from bash script - bash

Team,
I have a basic function and am getting error. basically, am trying to run kubectl via bash script. i even tried switching to its directory but still not woring.
node_cordon_info() {
kgn='kubectl get node'
if [ -z "$total_dgx_nodes_NotReady_state" ]; then
echo "No dgx_nodes_Ready_state found"
else
cd /usr/bin/
for dgx_node in "${total_dgx_nodes_Ready_state}"
kubectl get node $dgx_node --no-headers -o json | jq '.metadata.name,.metadata.labels."ns.com/cordon-reason"' | paste - - | xargs -l1 -- sh -c 'echo $1 https://jirasw.test.com/browse/$2' --
fi
}
output
./dgx-node-status-local.sh: line 94: syntax error near unexpected token `kubectl'
which kubectl
/usr/bin/kubectl
echo $PATH
/usr/bin/kubectl:/home/dtlu/deployments/:/usr/lib/go-1.10/bin:/usr/local/bin/kubectl:/home/dtlu/deployments/:/usr/lib/go-1.10/bin:/home/dtlu/deployments/:/usr/lib/go-1.10/bin:/home/dtlu/deployments/:/usr/lib/go-1.10/bin:/home/dtlu/deployments/:/usr/lib/go-1.10/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/dtlu/backup/nvidia/nsv/maglev-validations:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin

My bad: did not close the for loop.
node_cordon_info() {
kgn='kubectl get node'
if [ -z "$total_dgx_nodes_NotReady_state" ]; then
echo "No dgx_nodes_Ready_state found"
else
cd /usr/bin/
for dgx_node in "${total_dgx_nodes_Ready_state}"; do
kubectl get node $dgx_node --no-headers -o json | jq '.metadata.name,.metadata.labels."ns.com/cordon-reason"' | paste - - | xargs -l1 -- sh -c 'echo $1 https://jirasw.test.com/browse/$2' --
done
fi
}

Related

cd into a specific directory changes PATH variable

When I change directory (cd) into one specific directory (which contains a rails application) it changes the PATH variable, removing many directories from PATH including /bin, /usr/bin, and /usr/local/bin, after which I get many bash errors of "command not found" for commands like which, ls, grep, etc. It appears to be only that one directory which causes the problem, when I cd into it or cd from it. I don't see any obvious files in the directory which would be changing the PATH variable in this way. Before I enter the directory, my PATH looks like this:
$ echo $PATH
/usr/local/opt/node#10/bin:/usr/local/opt/postgresql#9.4/bin:/Users/cedric/.rbenv/shims:/Users/cedric/.rbenv/shims:/Users/cedric/.rvm/gems/ruby-2.3.7/bin:/Users/cedric/.rvm/gems/ruby-2.3.7#global/bin:/Users/cedric/.rvm/rubies/ruby-2.3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/cedric/.rvm/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin/AWS_Tools/AutoScaling-1.0.61.6/bin:/usr/local/bin/AWS_Tools/CloudWatch-1.0.20.0/bin:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/api/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/AWSDevTools/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/linux/python2.7/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/eb:/usr/local/mysql/bin:/Users/cedric/.rbenv/bin:/Users/cedric/.rbenv/shims:/usr/local/mysql/bin
After I enter the directory, my PATH looks like this:
cedric#Computer togo [develop] $ cd .
sed: illegal option -- r
usage: sed script [-Ealn] [-i extension] [file ...]
sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]
-bash: cat: command not found
-bash: cat: command not found
-bash: cut: command not found
cedric#Computer togo $ echo $PATH
/Users/cedric/.rvm/gems/ruby-2.3.7#togo/bin:/Users/cedric/.rvm/gems/ruby-2.3.7#global/bin:/Users/cedric/.rvm/rubies/ruby-2.3.7/bin:/Users/cedric/.rvm/bin:
-bash: cut: command not found
cedric#Computer togo $
This wasn't a problem before today. Any thoughts on what could be causing this?
Thank you
RESPONSES TO COMMENTS:
$ echo "$PROMPT_COMMAND"
update_terminal_cwd;
$ type update_terminal_cwd
update_terminal_cwd is a function
update_terminal_cwd ()
{
local SEARCH=' ';
local REPLACE='%20';
local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}";
printf '\e]7;%s\a' "$PWD_URL"
}
(seems like that's just replacing "%20" for " " whatever PWD_URL is.)
$ type cd returns
cd is a function
cd ()
{
__zsh_like_cd cd "$#"
}
and
$ type __zsh_like_cd
__zsh_like_cd is a function
__zsh_like_cd ()
{
\typeset __zsh_like_cd_hook;
if builtin "$#"; then
for __zsh_like_cd_hook in chpwd "${chpwd_functions[#]}";
do
if \typeset -f "$__zsh_like_cd_hook" > /dev/null 2>&1; then
"$__zsh_like_cd_hook" || break;
fi;
done;
true;
else
return $?;
fi
}
In the output of set I find:
chpwd_functions=([0]="__rvm_cd_functions_set")
...
__rvm_after_cd ()
{
\typeset rvm_hook;
rvm_hook="after_cd";
if [[ -n "${rvm_scripts_path:-}" || -n "${rvm_path:-}" ]]; then
source "${rvm_scripts_path:-$rvm_path/scripts}/hook";
fi
}
...
__rvm_cd_functions_set ()
{
__rvm_do_with_env_before;
if [[ -n "${rvm_current_rvmrc:-""}" && "$OLDPWD" == "$PWD" ]]; then
rvm_current_rvmrc="";
fi;
__rvm_project_rvmrc 1>&2 || true;
__rvm_after_cd || true;
__rvm_do_with_env_after;
return 0
}
There was a lot of output for set | grep sed (48 lines) so I searched for such output with PATH:
$ set | grep sed | grep -i path
\command \cat "$environment_file_path" | __rvm_grep -Eo "[^ ]+=[^;]+" | __rvm_sed -e 's/\$PATH/'"${PATH//\//\\/}"'/' -e 's/\${PATH}/'"${PATH//\//\\/}"'/';
rvm_silence_logging=1 "$rvm_scripts_path/gemsets" list strings | __rvm_sed "s/ (default)//; s/^/$current_ruby${rvm_gemset_separator:-#}/ ; s/#default// ;"
__rvm_sed -e 's/#.*$//g' -e 's#\[##g' -e 's#\]##g' < "$rvm_path/config/known" | sort -r | uniq;
<log>Usually this is caused by shell initialization files. Search for <code>PATH=...</code> entries.
PATH="$(\sed -E -e 's#/+#/#g' -e 's#/:#:#' <<<$PATH)";
PATH="$(\sed -r -e 's#/+#/#g' -e 's#/:#:#' <<<$PATH)";
__rvm_sed_i "$__rvmrc_warning_path" -e "\#^${1}\$# d" -e '/^$/ d';
__rvm_sed_i "$__rvmrc_warning_path" -e "\#/${__rvmrc_type}\$# d" -e '\#^$# d';
__rvm_sed_i "$__rvmrc_warning_path" -e "\#^${1}\$# d" -e '\#^$# d';
Also, searching for places where PATH is set, it seems like they are all including the original value of PATH in the new value:
$ set | grep "\<PATH *="
PATH=/usr/local/opt/node#10/bin:/usr/local/opt/postgresql#9.4/bin:/Users/cedric/.rbenv/shims:/Users/cedric/.rbenv/shims:/Users/cedric/.rvm/gems/ruby-2.3.7/bin:/Users/cedric/.rvm/gems/ruby-2.3.7#global/bin:/Users/cedric/.rvm/rubies/ruby-2.3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/cedric/.rvm/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin/AWS_Tools/AutoScaling-1.0.61.6/bin:/usr/local/bin/AWS_Tools/CloudWatch-1.0.20.0/bin:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/api/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/AWSDevTools/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/linux/python2.7/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/:/usr/local/bin/AWS_Tools/AWS-ElasticBeanstalk-CLI-2.6.3/eb/macosx/python2.7/eb:/usr/local/mysql/bin:/Users/cedric/.rbenv/bin:/Users/cedric/.rbenv/shims:/usr/local/mysql/bin
PATH="$2:$PATH"
PATH="$PATH:$2"
PATH="${rvm_user_path_prefix}:$PATH";
PATH="$PATH:${rvm_bin_path}";
PATH="${rvm_bin_path}:$PATH";
printf "%b" "export PATH=\"${__path}:\$PATH\"\n" > "$file_name";
PATH="${_new_path[*]}:$PATH";
env | __rvm_grep -E '^GEM_HOME=|^GEM_PATH=|^PATH=';
<log>Usually this is caused by shell initialization files. Search for <code>PATH=...</code> entries.
PATH="${save_PATH}";
PATH="$(\sed -E -e 's#/+#/#g' -e 's#/:#:#' <<<$PATH)";
PATH="$(\sed -r -e 's#/+#/#g' -e 's#/:#:#' <<<$PATH)";
command_to_run=(/usr/bin/env PATH="${PATH}${missing_paths}" "${command_to_run[#]}");
PATH="${_OLD_VIRTUAL_PATH}";
PATH="${__path_prefix:-}${__path_prefix:+:}$__save_PATH${__path_suffix:+:}${__path_suffix:-}";
Does any of the above raise red flags as a possible culprit? Should I be checking for something more specific?
RESPONSE TO #Roadowl (in that directory):
$ /bin/ls -la -- -*
ls: -*: No such file or directory
chruby can do this, using preexec_function in zsh and trap in bash. My answer from https://github.com/postmodern/chruby/blob/master/share/chruby/auto.sh:
You're probably sourcing https://github.com/postmodern/chruby/blob/master/share/chruby/auto.sh
which includes a trap command in bash and a preexec_function command in zsh to run chruby_auto when you change directory.
What chruby_auto does is look for the .ruby_version file you have and set ruby from that file by changing path variables.

Why is exit my status valid in command line but not within bash script? (Bash)

There are a few layers here, so bear with me.
My docker-container ssh -c"echo 'YAY!'; exit 25;" command executes echo 'YAY!'; exit 25; in my docker container. It returns:
YAY
error: message=YAY!
, code=25
I need to know if the command within the container was successful, so I append the following to the command:
docker-container ssh -c"echo 'YAY!'; exit 25;" >&1 2>/tmp/stderr; cat /tmp/stderr | grep 'code=' | cut -d'=' -f2 | { read exitStatus; echo $exitStatus; }
This sends the stderr to /tmp/stderr and, with the echo $exitStatus returns:
YAY!
25
So, this is exactly what I want. I want the $exitStatus saved to a variable. My problem is, I am placing this into a bash script (GIT pre-commit) and when this exact code is executed, the exit status is null.
Here is my bash script:
# .git/hooks/pre-commit
if [ -z ${DOCKER_MOUNT+x} ];
then
docker-container ssh -c"echo 'YAY!'; exit 25;" >&1 2>/tmp/stderr; cat /tmp/stderr | grep 'code=' | cut -d'=' -f2 | { read exitStatus; echo $exitStatus; }
exit $exitStatus;
else
echo "Container detected!"
fi;
That's because you're setting the variable in a pipeline. Each command in the pipeline is run in a subshell, and when the subshell exits the variable are no longer available.
bash allows you to run the pipeline's last command in the current shell, but you also have to turn off job control
An example
# default bash
$ echo foo | { read x; echo x=$x; } ; echo x=$x
x=foo
x=
# with "lastpipe" configuration
$ set +m; shopt -s lastpipe
$ echo foo | { read x; echo x=$x; } ; echo x=$x
x=foo
x=foo
Add set +m; shopt -s lastpipe to your script and you should be good.
And as Charles comments, there are more efficient ways to do it. Like this:
source <(docker-container ssh -c "echo 'YAY!'; exit 25;" 2>&1 1>/dev/null | awk -F= '/code=/ {print "exitStatus=" $2}')
echo $exitStatus

grep bashrc of other user for checking variable

I'm trying to grep the bashrc of a user for check if a line already exists.
I've tried this:
if [ [ su - ${1} -c "cat ~/.bashrc | grep ${2} | wc -c | tr -d ' '" ] -gt 0 ]
if [ su - ${1} -c "cat ~/.bashrc | grep ${2} | wc -c | tr -d ' '" ]
$1 is a username
$2 is the VarName
In exec
+ '[' su - user -c 'cat ~/.bahsrc | grep PATH | wc -c | tr -d '\'' '\''' ']'
line xxx: [: too many arguments
Is it possible to do that like this ? Do I need to use return values (actually $? = 0 for all) ?
If you're just checking that a line exists, there's no need to involve wc or tr or anything else; this should suffice:
if su - ${1} -c "grep -q '${2}' ~/.bashrc" ; then
echo line exists in file
else
echo line does not exist in file
fi
This will echo line exists in file if the contents of $2 are found in ~/.bashrc.
To help understand what's going on here, remember that the syntax of the if statement is (from the bash man page):
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
Where list is one or more commands. In this case, we're using the exit code from the grep command to determine the "truth" of the expression.

Bash Script issue, command not found, PATH seems to be correct

I have a issue with my Script, i am just trying to fingure out if my screen session is running or not (line 19).
The rest of the script is working.
#!/bin/bash
echo $PATH // /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
echo "0"
content=$(wget http://interwebs.com/index.php?page=count -q -O -)
z=$(($content / 5))
z=$(($z + 1))
echo $z // 4
lockfile=/var/tmp/mylock
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; then
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
# do stuff here
x=1
count=0
while [ $x -le $z ]
do
$req ="$(ps -ef | grep -i mystatus$count | grep -v grep)"
if [ "$req" = "" ]; then
# run bash script
screen -amds mystatus$count /usr/bin/wget --spider interwebs.com/index.php?page=cronwhatsoever$(( $count +1))-$(( $count +5))
else
echo "Cron running"
fi
x=$(( $x + 1 ))
count=$(( $count +5))
done
# clean up after yourself, and release your trap
rm -f "$lockfile"
trap - INT TERM EXIT
else
echo "Lock Exists: $lockfile owned by $(cat $lockfile)"
fi
sleep 15
It returns line 19: =: command not found. Actually running:
ps -ef | grep -i bukkit | grep -v grep
Works without issues if i run it directly in my Terminal, so any idea how to solve this issue?
I guess it something PATH related but grep is located in /bin/grep.
$req ="$(ps -ef | grep -i mystatus$count | grep -v grep)"
should be
req="$(ps -ef | grep -i mystatus$count | grep -v grep)"
Don't use $ on the left-hand side of an assignment, and you must not have spaces around the =

rake - running shell command returns error

I am trying to run in Rake the following shell command:
sh "d='jps -l | grep jar | cut -d ' ' -f 1'; if [ -z \"$d\" ]; then :; else kill \"$d\"; fi;"
However I get:
sh: -f 1: not found
If I run it in linux shell it works fine.
What is wrong?
I interpreted your question wrong earlier. This is what you want.
d='jps -l | grep jar | cut -d " " -f 1; if [ -z "$d" ]; then :; else kill "$d"; fi;'
system(d)
OR
If you want output of the command (which I guess you don't in this case)
output = `jps -l | grep jar | cut -d " " -f 1; if [ -z "$d" ]; then :; else kill "$d"; fi;`
You need to escape your single quotes and quote the whole string:
d='jps -l | grep jar | cut -d \' \' -f 1; if [ -z "$d" ]; then :; else kill "$d"; fi;'

Resources