Skip to content

Instantly share code, notes, and snippets.

@anis016
Last active October 6, 2021 10:13
Show Gist options
  • Save anis016/01eb19eb80330980701a4479b4f323d4 to your computer and use it in GitHub Desktop.
Save anis016/01eb19eb80330980701a4479b4f323d4 to your computer and use it in GitHub Desktop.
Useful bash script
This gist contains useful bash scripts
containsElement () {
local _flag="false"
local match="$1"
shift
for item; do [[ "$item" == "$match" ]] && _flag="true"; done
echo ${_flag}
}
array=("something to search for" "a string" "test2000")
_found=$(containsElement "a string" "${array[@]}")
if [[ ${_found} == "true" ]]; then
echo "found"
else
echo "not found"
fi
mkdir hello_world
mkdir hello_world/dir1
mkdir hello_world/dir2
tar --create --remove-files hello_world | gzip > hello_world.tar.gz
[tar --create --remove-files __FOLDER__NAME__ | gzip > __FILE__NAME__.tar.gz]
tar -czf hello_world.tar.gz --remove-files hello_world
[tar -czf __FILE__NAME__.tar.gz --remove-files __FOLDER__NAME__]
tar -xzf hello_world.tar.gz; rm -rf hello_world.tar.gz
https://unix.stackexchange.com/questions/22273/how-to-use-regex-as-field-separator-in-awk
# ignores heading and checks for number of \t in each line
awk 'NR!=1' test.txt | awk -F '\t' '{ print NF-1 }'
# doesn't ignore heading
awk -F '\t' '{ print NF-1 }' test.txt
# ignores heading and checks for number of all kind of spaces in each line
awk 'NR!=1' test.txt | awk -F '[[:space:]]*' '{ print NF-1 }'
$ cat test.txt
this is heading
hello world space one two three five
# in machine1
$ ssh-keygen -t rsa
> generates: id_rsa, id_rsa.pub
# copy the id_rsa.pub from the machine1 to the machine2 via a jumphost or an intermediary machine
# in machine2
$ mkdir /root/.ssh (in case if .ssh is not present)
$ chmod 700 /root/.ssh (in case if .ssh is not present)
$ cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
$ chmod 640 /root/.ssh/authorized_keys
This does passwordless access from machine1 -> machine2. If need to do the other way around then follow the same other way around.
$ touch call.sh
#!/usr/bin/env bash
set -E
_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${_dir}/main.sh"
_file="${_dir}/$(basename "${BASH_SOURCE[0]}")"
_base="$(basename "${_file}" .sh)"
trap "cleanup ${_base}" ERR
just_run_something "message this"
touch main.sh
#!/usr/bin/env bash
function cleanup() {
local _BASE="$1"
echo "_BASE: ${_BASE}"
echo "Caught Signal ... cleaning up."
rm -rf /tmp/created
echo "Done cleanup ... quitting."
}
function just_run_something {
echo "$1"
# touch /root/created # fail things
touch /tmp/created
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment