Skip to content

Instantly share code, notes, and snippets.

@lcaballero
Last active August 31, 2017 15:23
Show Gist options
  • Save lcaballero/90e393b4d26dfa8c72a7140439010f8f to your computer and use it in GitHub Desktop.
Save lcaballero/90e393b4d26dfa8c72a7140439010f8f to your computer and use it in GitHub Desktop.
Some bash snippets.
# :create-user :password :wheel :sudoer :sudo
sudo useradd -G wheel -p "$(openssl passwd)" "admin"
# grep stuff
find . | grep -vE "(.git|./wiki)" | grep -E "\.sh$" | xargs -0 grep -ni "batman"
# :here-doc :variable :here
# save multi-line value from 'here doc' into bash variable
VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)
echo "$VAR"
# :name-refs
$ dump_array() {
local -n a=$1
for i in "${!a[@]}"; do printf "%s\t%s\n" "$i" "${a[$i]}"; done
}
$ declare -a indexed=(a b c d)
$ declare -A associative=([foo]=bar [baz]=qux)
$ dump_array indexed
0 a
1 b
2 c
3 d
$ dump_array associative
baz qux
foo bar
# array concat and func parameters and array access
#!/bin/bash
#set -e
declare -a FILES
create_art() {
echo "\$# : '$#'"
local name1 name2
local "${@}" > /dev/null # 'a b' not a valid identifier (fails only with set -e)
local files=(${*:3})
echo "\$name1: '$name1"
echo "\$name2: '$name2"
echo "\$files: '$files"
echo "\${files[0]}: '${files[0]}'"
echo "\${files[1]}: '${files[1]}'"
echo "\${files[2]}: '${files[2]}'"
echo "\${files[3]}: '${files[3]}'"
echo "\${files[4]}: '${files[4]}'"
echo "\${files[30]}: '${files[30]}'"
echo "\${files[-1]}: '${files[-1]}'"
echo "\${files[-2]}: '${files[-2]}'"
echo "\${files[-3]}: '${files[-3]}'"
# echo "\${files[-4]}: '${files[-4]}'" # bad array subscript
echo "\${files[@]}: '${files[@]}'"
FILES+="${files[@]}"
echo "\${files[@]}: '${files[@]}'"
}
run_it() {
create_art name1=abc name2=xyz "a b" c
}
run_it
# param args debug
#!/bin/bash
kvp() {
if [ "$1" == "-e" ]; then
echo -n "echo "
shift 1
fi
for name in $* ; do
echo -n "$name=\$$name "
done
}
# This would be the case where you know the set of parameters and are
# trying to debug or pass most of them all of the time.
_params(){
local pairs=$(kvp app godir dir branch versionNumber \
buildNumber cwd excludes path \
org artifact_dir artifacts_dir PWD WORKSPACE \
os)
if [ "$1" == "-e" ]; then
echo "echo $pairs"
else
echo "$pairs"
fi
}
call1() {
local org app
local "${@}" > /dev/null
echo "call1: $org $app"
}
do_it() {
local call="$1"
local pairs="$2"
eval "$call" "$pairs"
}
example_call() {
shift 1
local org=bruce
local app=wayne
do_it call1 "$(eval $(_params -e))"
}
# execute with ./_.sh example_kvp org=zzz
example_kvp() {
shift 1 # only here for the '$1 $*' invocation.
local org app
local "${@}" > /dev/null
do_it call1 "$(eval $(kvp -e org app))"
}
$1 $*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment