This is a slowly growing collection of hopefully useful and reusable shell functions and patterns. https://code.jan.io/jan/jans_shell_utils
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Jan Lehnardt b1e59e9d4a first draft 3 년 전
.gitignore init 3 년 전
README.md first draft 3 년 전
lib.sh first draft 3 년 전
test.sh first draft 3 년 전
wait_for_pid_exit.sh first draft 3 년 전
wait_for_url.sh first draft 3 년 전

README.md

Jan’s Shell Utilities

I’m coming across having to write the same shell script bits occasionally, and I got tired of jumping backwards through my projects to find the latest version, so here is a repository.

Goals

  • Write once (here) and copypasta everywhere.
  • sh compatible if possible

Functions

wait_for_url $url $duration $iterations

Wait for a particular URL to be available using curl. Wait $duration seconds between attempts, try $iterations times. Defaults to 1 seconds and 3 times.

Signature:

wait_for_url url<string> [iterations<int> duration<int>]

Usage:

source ./wait_for_url.sh

# try 3 times, 1s apart
wait_for_url http://127.0.0.1:5984

# try 5 times, 1s apart
wait_for_url http://127.0.0.1:5984 5 3

# try 5 times, 3s apart
wait_for_url http://127.0.0.1:5984 5 3

wait_for_pid_exit $pid $duration $iterations

Wait for a particular PID to exit. Wait $duration seconds between attempts, try $iterations times. Defaults to 1 seconds and 3 times.

Signature:

wait_for_pid_exit pid<int> [iterations<int> duration<int>]

Usage:

source ./wait_for_pid_exit.sh

# try 3 times, 1s apart
wait_for_pid_exit 3618

# try 5 times, 1s apart
wait_for_pid_exit 3618 5 3

# try 5 times, 3s apart
wait_for_pid_exit 3618 5 3

error_and_exit $message

Prints an error message and then exits with exit code 1.

Signature:

error_and_exit [message<string>]

Usage:


source ./lib

# print message, then exit
error_and_exit "this did not work"

TODO:

  • make exit code variable
    • probably as error_and_exit "msg" 17

assert_arg $arg

Assert if a particular argument has been passed to a function. Combine with && and || for error handling and setting of defaults for optional arguments.

Signature:

assert_arg arg<any>

Usage:

source ./lib.sh


# fail if arg is missing
function my_fun () {
	assert_arg $1 && url=$1 || error_and_exit "error 'url' missing"
	# now $url is available
}

# set arg to default value if missing
function my_fun () {
	assert_arg $1 && iterations=$1 || iterations=5
	# now $iterations is available
}