How to get script directory in POSIX sh?

The POSIX-shell (sh) counterpart of $BASH_SOURCE is $0. see bottom for background info Caveat: The crucial difference is that if your script is being sourced (loaded into the current shell with .), the snippets below will not work properly. explanation further below Note that I’ve changed DIR to dir in the snippets below, because it’s … Read more

source command not found in sh shell

/bin/sh is usually some other shell trying to mimic The Shell. Many distributions use /bin/bash for sh, it supports source. On Ubuntu, though, /bin/dash is used which does not support source. Most shells use . instead of source. If you cannot edit the script, try to change the shell which runs it.

How does Ctrl-C terminate a child process?

Signals by default are handled by the kernel. Old Unix systems had 15 signals; now they have more. You can check </usr/include/signal.h> (or kill -l). CTRL+C is the signal with name SIGINT. The default action for handling each signal is defined in the kernel too, and usually it terminates the process that received the signal. … Read more

Calling shell functions with xargs

Exporting the function should do it (untested): export -f echo_var seq -f “n%04g” 1 100 | xargs -n 1 -P 10 -I {} bash -c ‘echo_var “$@”‘ _ {} You can use the builtin printf instead of the external seq: printf “n%04g\n” {1..100} | xargs -n 1 -P 10 -I {} bash -c ‘echo_var “$@”‘ … Read more

How to redirect output of an entire shell script within the script itself?

Addressing the question as updated. #…part of script without redirection… { #…part of script with redirection… } > file1 2>file2 # …and others as appropriate… #…residue of script without redirection… The braces ‘{ … }’ provide a unit of I/O redirection. The braces must appear where a command could appear – simplistically, at the start … Read more

Count occurrences of a char in a string using Bash

you can for example remove all other chars and count the whats remains, like: var=”text,text,text,text” res=”${var//[^,]}” echo “$res” echo “${#res}” will print ,,, 3 or tr -dc ‘,’ <<<“$var” | awk ‘{ print length; }’ or tr -dc ‘,’ <<<“$var” | wc -c #works, but i don’t like wc.. 😉 or awk -F, ‘{print NF-1}’ … Read more