r_bash
44 subscribers
329 photos
16 videos
8.36K links
Download Telegram
Built yet another public IP lookup
https://redd.it/1rrco97
@r_bash
A simple, compact way to declare command dependencies

I wouldn't normally get excited at the thought of a shell script tracking its own dependencies, but this is a nice, compact pattern that also feels quite a bit like the usual dependency *import* mechanisms of more modern languages. There's a loose sense in which importing *is* what you're doing, essentially asking the system if you can pull in the requested command, and of course, as such, you're also documenting your required commands upfront.

declare -r SCRIPT_NAME="${0##*/}"

require() {
local -r dependency_name="$1"
local dependency_fqdn

if ! dependency_fqdn="$(command -v "$dependency_name" 2>/dev/null)"; then
echo "Error: dependency $dependency_name is not installed"
echo "$SCRIPT_NAME cannot run without this, exiting now"
exit 1
fi

printf -v "${dependency_name^^}_CMD" '%s' "$dependency_fqdn"
}

require pass
echo $PASS_CMD

The resulting variable assignment gives you a convenient way to pass around the full path of the command. It's a bit of magic at first blush, but I'd also argue it's nothing that a doc comment on the function couldn't clear up.

Just a cool trick that felt worth a share.

**EDIT:** swapped out `which` for `command`, a Bash builtin, per suggestion by /u/OneTurnMore.

https://redd.it/1rrdofl
@r_bash
I built a free Bash PS1 prompt generator — looking for Linux user feedback

Hi everyone, I built a small web tool to help generate custom Bash PS1 prompts visually.

You can add prompt elements (date/time, user, host, path, git info, symbols), style them with colors/text attributes, reorder them, and instantly copy the final prompt code.

I just published the first public release and I’d really appreciate feedback from Linux users:

* Is the generated output clean and practical for real shells?
* Which prompt elements are missing?
* Any UX issues or bugs on your distro/browser?

Project link: [https://neiki.eu/bash-prompt-generator/](https://neiki.eu/bash-prompt-generator/)
GitHub: [https://github.com/jindrichstoklasa/bash-prompt-generator](https://github.com/jindrichstoklasa/bash-prompt-generator)

Thanks — even short feedback is super helpful.

https://redd.it/1rr3eie
@r_bash
Parsing duf (partial) through to my ~/.bashrc
https://redd.it/1rrjutx
@r_bash
Beginner Question automate install pkgs

I'm install Termux fresh and have gathered a list of tools below which I want to feed into: pkg install <contents of list.txt> cleanly line by line or glob.
list.txt:

tldr
ncdu
python-pip
fzf
wget
curl
p7zip
tar
fd
ripgrep
rclone
nano
tmux
cava
cmatrix
zip
unzip
cmake
mplayer
nmap
make
pkg-config
nodejs
tcpdump
netcat-openbsd
yt-dlp
busybox
proot-distro
htop
eza
git
zellij
lolcat
fastfetch
bat
dua
rsync
starship
mpv
ffmpeg
dust
duf
bottom
neovim
procs
lazygit
tree
vim
openssh
clang
python

What's the proper syntax to pass to pkg install list.txt 📚

pkg install $(cat list.txt) correct?

https://redd.it/1rrohj7
@r_bash
Parsing both options and args with spaces on function

Hi!

I defined this function in my .bashrc:

function mytree {
/usr/bin/tree -C $* | less -R -S
}

This works well so long as none of the arguments have spaces. If I quote the args string variable, "$* I can pass directories with spaces, but no further options; for example, if I use "$*, this fails: mytree -L 2 "/dir/with spaces". It tries to open /dir/with/ and spaces/.

Is there a way around this? I want to be able to pass options and dirs with spaces. Please refrain from suggesting I change a dir's name, I also use such functions at work and cannot do that on the servers.

Thanks!

https://redd.it/1rqwra5
@r_bash
Stop holding the left arrow key to fix a typo. You've had fc the whole time.


# you just ran this
aws s3 sync /var/backups/prod s3://my-buket/prod --delete --exclude "*.tmp"
# ^typo


Hold for ten seconds. Miss it. Hold again. Fix it. Run it. Wrong bucket. Rage.

Or:

fc


That's it. fc opens your last command in $EDITOR.Navigate directly to the typo, fix it, save and quit — the corrected command executes automatically.

Works in bash and zsh. Has been there since forever. You've just never needed to know the name.

Bonus: fc -l shows your recent history. fc -s old=new does inline substitution without opening an editor. But honestly, just fc alone is the one you'll use every week.

https://redd.it/1rpwcad
@r_bash
Depending on the client I use to Telnet or NCAT ascii.bigjobby.com 2323, I get different results. NCAT generally works as intended across clients but Telnet is sketchy, sometimes I get colour and sometimes I don't. Is colour via Telnet even possible or am I silently falling back to NCAT?



https://redd.it/1rqtx85
@r_bash
Neglected !! party tricks

Everybody knows about using !! to add sudo to your previous command, but there are a couple other things I constantly use it for. So this is just a little PSA in case it never occured to you:

1. grep results

Say I want to search a bunch of files for a string, and then open all files containing that string in my editor.

I want to check the search results first, and I never get the exact search correct on my first try anyway, so I'll run a series of commands that might look like...

grep -rn . -e "mystring"
...
grep -rn . -e "my.\?string"
...
grep -Rni . -e "my.\?string"
...

Checking the results each time, until I have exactly the set of files that I want.

Here's the trick: now add the "-l" flag to grep to get just the file paths:

grep -Rnil . -e "my.\?string"

Now when you use !!, you'll get all those filenames. Therefore we can just do vim -p $(!!) to get all those files opened in tabs in vim.

2. with which

Sometimes I want to read or edit a script that's on my computer.

To find it, I run which some-command. This confirms that it exists under that name, and that it's an actual script and not an alias or shell function.

Now, we can just use vim $(!!) or cat $(!!) or whatever to open it.

https://redd.it/1ry9vhm
@r_bash
How do you print "Here document" or "Here Strings" directly?

Edit (Solution): There are two solutions here, depending on the case in which you are.
- Case 1: You use Here Document to print some multiline text.
Don't do that.
Instead, you can just do this:
 printf "%s\r\n"\
"This is the first line."\
"This is the second line."

# This solution has just one annoyance which is that you have to enclose all lines in double quotes and end with a slash.
# But compare this to here documents which don't allow any special characters to be used, sort of.

- Case 2: You actually are getting some text from somewhere and you are wrapping it to make it a Here Document or something like that.
I would say that there is a high chance the first solution is still more optimal but if you don't feel that, the solution below is your hero.

Credit to: u/OnlyEntrepreneur4760, for reminding me that we can use \ to write a command in multiple lines.
Something I forgot since I consider it a bad habit and stopped using.
But it makes sense here.

---


{ printf "%s\n" "$(< /dev/stdin)"; } <<-EOF
This is first line.
This is second line.
This is third line.
EOF



Is this how everyone does it or is there a better way to print it directly without storing the "here document" or "here string" to a variable or a file?

PS: WITH ONLY USING BASH BUILTINS

https://redd.it/1rxvbpc
@r_bash
Environment Variables

I am currently trying to understand bash and am learning with linuxjourney. However, I am now kind of stuck at understanding environment variables. Can someone tell me if I am understanding this right?

Basically, environment variables are variables, that store information. Now this can be either information (like PATH stores it) that points toward certain directories from where the shell would get the program needed for a command or it is a variable storing information about which directory I am currently in like PWD variable and so on. These variables can either temporarly changed by "export PATH = /example" which would only change the variable for the current session or they can be permanently changed by altering the configuration files.

Also the environment variables are built from these configuration files on booting (or opening shell idk pls help) and can as mentioned be configured to behave different permanently by altering the config files.

What I still completely struggle with is why does one variable actively tell the shell where to look for program files like PATH and other are just storing information like PWD. ChatGPT said that there are functional/operational variables like PATH and informational/state variables like PWD. Can someone confirm the validity of this information?

As you see I am completely new to this and I am really lost so any help will make me happy, thanks!

https://redd.it/1ry5vbp
@r_bash
Tip Stop mashing the Up arrow: Filtered History Search with Alt+Up/Down

If you have a 100-character xrandr command or a complex docker string that you use intermittently, Ctrl+R can be a clunky way to find it. Instead, you can configure Bash to perform Incremental History Searching.

This allows you to type the first few letters of a command (e.g., xr) and use a modifier key to cycle only through previous commands that start with those letters.

1. The Configuration Add these lines to your ~/.inputrc.
2. We use the Alt (Meta) key to avoid overwriting the standard "Up/Down" scrolling behavior:

Bash

# Alt+Up: Search forward or backward for commands starting with what you've typed:

"\e[1;3A": history-search-backward

# Alt+Down: Search backward for commands starting with what you've typed:
"\e[1;3B": history-search-forward



Wait, why not just use Ctrl+S to search forward? Standard terminals use Ctrl+S for "XOFF" (flow control), which instantly freezes your terminal output (requiring Ctrl+Q to unfreeze). While you can disable this with stty -ixon, mapping forward-search to Alt+Down is a much cleaner "modern" solution that doesn't mess with legacy TTY settings.

2. Apply it Instantly You don't need to reboot or restart your shell. Tell the Readline library to reload its configuration immediately:

Bash

bind -f ~/.inputrc

3. The Workflow Type xrandr (or even just xr).

Press Alt+Up.

It will skip over every ls, cd, and git command in your history and jump straight to your last complex xrandr call.

Press Alt+Up again to go further back in time through only the xrandr entries.

Why Alt+Up/Down? Most tutorials suggest mapping the standard Up/Down arrows (\\e[A), but that breaks the ability to simply scroll back through the last few (unfiltered) commands. Mapping it to the Alt modifier gives you the best of both worlds: standard history for quick tasks, and filtered search for the complex stuff.

https://redd.it/1rx8pz3
@r_bash
need help getting sgrep to work in a script file

this command will find all references to emdash in a swath of files and report back which files contain the reference.

sgrep -o '%r\n' '"\"" _quote_ "\"" in ("name[Group1]" .. "\n" in outer("{" .. "}" containing "emdash"))' /usr/share/X11/xkb/symbols/??



but i want to use this in a script and feed it a variable that i read from stdin for the search string using something like

read sym

and then use $sym in place of the fixed string emdash

but it returns nothing when i use

containing "$sym"

so i also tried it without the quotes, and it REALLY did not like that

Parse error in command line expression column 77 :
Invalid character
" _quote_ "\"" in ("name[Group1]" .. "\n" in outer("{" .. "}" containing $sym))
^
No query to evaluate. Bailing out.



so then i tried containing "$(echo $sym)"

and got nothing back

is sgrep not capable of evaluating variables? or what?



https://redd.it/1rxjvl8
@r_bash
Any of you want to critique the postgres utils script I wrote?

**`logger_utils.sh`**
```
#!/usr/bin/env bash
#
# Contains functions for logging different types of messages.
#######################################
# Determine if the terminal supports color.
# Arguments:
# None
# Returns:
# 0 if color is supported, 1 otherwise.
#######################################
function supports_color() {
# stderr is a terminal?
[[ -t 2 ]] || return 1
# Terminal claims color support
[[ -n "${TERM:-}" && "${TERM}" != "dumb" ]] || return 1
# Respect NO_COLOR standard
[[ -z "${NO_COLOR:-}" ]] || return 1
return 0
}

#######################################
# Define color constants based on terminal support.
# Globals:
# COLOR_RED, COLOR_GREEN, COLOR_NONE
#######################################
if supports_color || [[ -n "${force_color:-}" ]]; then
readonly COLOR_RED='\033[0;31m'
readonly COLOR_GREEN='\033[0;32m'
readonly COLOR_YELLOW='\033[0;33m'
readonly COLOR_NONE='\033[0m'
else
readonly COLOR_RED=''
readonly COLOR_GREEN=''
readonly COLOR_YELLOW=''
readonly COLOR_NONE=''
fi

#######################################
# Internal logging function.
# Arguments:
# 1: Message string
# 2: Status string (e.g., INFO, ERROR)
# 3: Color escape code
# Outputs:
# Writes formatted log to stderr.
#######################################
function log_message() {
local -r message="$1"
local -r status="${2:-INFO}"
local -r color="${3:-${COLOR_NONE}}"
local -r timestamp="$(date +"%Y-%m-%dT%H:%M:%S%z")"
# Output to stderr (>&2) as per the guide's recommendation for diagnostic info.
printf "[%s] [%b%s%b] %s\n" \
"${timestamp}" \
"${color}" "${status}" "${COLOR_NONE}" \
"${message}" >&2
}

#######################################
# Log an error message in red.
# Arguments:
# 1: Message string
#######################################
function log_error() {
log_message "$1" "ERROR" "${COLOR_RED}"
}

#######################################
# Log an info message in green.
# Arguments:
# 1: Message string
#######################################
function log_info() {
log_message "$1" "INFO" "${COLOR_GREEN}"
}

#######################################
# Log a warning message in yellow.
# Arguments:
# 1: Message string
#######################################
function log_warn() {
log_message "$1" "WARN" "${COLOR_YELLOW}"
}


```

**`postgres_utils.sh`**
```
#!/usr/bin/env bash
#
# Contains functions for common postgresql database operations

# shellcheck source=/dev/null
source "${HOME}/Desktop/utils/src/logger_utils.sh"

function run_createdb() {
if [[ -z "$(command -v createdb)" ]]; then
log_error "createdb command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_createdb <silent> <host> <port> <user> <database> [additional createdb flags]"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_user="$4"
local -r postgres_database="$5"
shift 5

local -a createdb_flags=(
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_user}"
)

createdb_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing createdb on database: ${postgres_database}, host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_user} with flags: ${createdb_flags[*]}"

if createdb "${createdb_flags[@]}" "${postgres_database}"; then
[[ "${silent}" = false ]] && log_info "createdb command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "createdb command execution failed"
return 1
fi
}

function run_createuser() {
if [[ -z "$(command -v createuser)" ]]; then
log_error "createuser command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_createuser <silent> <host> <port> <superuser> [additional createuser
flags] <user>"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_superuser="$4"
local -r postgres_user="$5"
shift 5

local -a createuser_flags=(
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_superuser}"
)

createuser_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing createuser on host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_superuser} with flags: ${createuser_flags[*]}"

if createuser "${createuser_flags[@]}" "${postgres_user}"; then
[[ "${silent}" = false ]] && log_info "createuser command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "createuser command execution failed"
return 1
fi
}

function run_dropdb() {
if [[ -z "$(command -v dropdb)" ]]; then
log_error "dropdb command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_dropdb <silent> <host> <port> <user> <database> [additional dropdb flags]"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_user="$4"
local -r postgres_database="$5"
shift 5

local -a dropdb_flags=(
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_user}"
)

dropdb_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing dropdb on database: ${postgres_database}, host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_user} with flags: ${dropdb_flags[*]}"

if dropdb "${dropdb_flags[@]}" "${postgres_database}"; then
[[ "${silent}" = false ]] && log_info "dropdb command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "dropdb command execution failed"
return 1
fi
}

function run_dropuser() {
if [[ -z "$(command -v dropuser)" ]]; then
log_error "dropuser command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_dropuser <silent> <host> <port> <superuser> [additional createuser flags] <user>"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_superuser="$4"
local -r postgres_user="$5"
shift 5

local -a dropuser_flags=(
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_superuser}"
)

dropuser_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing dropuser on host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_superuser} with flags: ${dropuser_flags[*]}"

if dropuser "${dropuser_flags[@]}" "${postgres_user}"; then
[[ "${silent}" = false ]] && log_info "dropuser command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "dropuser command execution failed"
return 1
fi
}

function run_pg_dump() {
if [[ -z "$(command -v pg_dump)" ]]; then
log_error "pg_dump command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_pg_dump <silent> <host> <port> <user> <database> [additional pg_dump flags]"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_user="$4"
local -r postgres_database="$5"
shift 5

local -a pg_dump_flags=(
"--dbname=${postgres_database}"
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_user}"
)

pg_dump_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing pg_dump on database: ${postgres_database}, host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_user} with flags: ${pg_dump_flags[*]}"

if pg_dump
"${pg_dump_flags[@]}"; then
[[ "${silent}" = false ]] && log_info "pg_dump command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "pg_dump command execution failed"
return 1
fi
}

function run_pg_restore() {
if [[ -z "$(command -v pg_restore)" ]]; then
log_error "pg_restore command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 6 ]]; then
log_error "Usage: run_pg_restore <silent> <host> <port> <user> <database> [additional pg_restore flags] <filename>"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_user="$4"
local -r postgres_database="$5"
local -r filename="$6"
shift 5

local -a pg_restore_flags=(
"--dbname=${postgres_database}"
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_user}"
)

pg_restore_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing pg_restore on database: ${postgres_database}, host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_user} with flags: ${pg_restore_flags[*]}"

if pg_restore "${pg_restore_flags[@]}" "${filename}"; then
[[ "${silent}" = false ]] && log_info "pg_restore command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "pg_restore command execution failed"
return 1
fi
}

function run_psql() {
if [[ -z "$(command -v psql)" ]]; then
log_error "psql command not found. Please ensure PostgreSQL client is installed."
return 1
fi

if [[ "$#" -lt 5 ]]; then
log_error "Usage: run_psql <silent> <host> <port> <user> <database> [additional psql flags]"
return 1
fi

local -r silent="${1:-false}"
local -r postgres_host="$2"
local -r postgres_port="$3"
local -r postgres_user="$4"
local -r postgres_database="$5"
shift 5

local -a psql_flags=(
"--dbname=${postgres_database}"
"--host=${postgres_host}"
"--port=${postgres_port}"
"--username=${postgres_user}"
)

psql_flags+=("$@")

[[ "${silent}" = false ]] && log_info "Executing psql on database: ${postgres_database}, host: ${postgres_host}, port: ${postgres_port}, username: ${postgres_user} with flags: ${psql_flags[*]}"

if psql "${psql_flags[@]}"; then
[[ "${silent}" = false ]] && log_info "psql command executed successfully"
return 0
else
[[ "${silent}" = false ]] && log_error "psql command execution failed"
return 1
fi
}

```

- This is how I use the above script

**test.sh**
```
#!/usr/bin/env bash

# shellcheck source=/dev/null
source "${HOME}/Desktop/utils/src/postgres_utils.sh"

function test_createdb() {
local database="$1"
local user="$2"

local host="localhost"
local port=5432

if ! run_createdb \
"false" \
"${host}" \
"${port}" \
"${user}" \
"${database}" \
"--encoding=UTF-8" \
"--owner=${user}" \
"--username=${user}"; then
exit 1
fi
}

function test_createuser() {
local user="$1"
local host="localhost"
local port=5432
local superuser="root"
if ! run_createuser \
"false" \
"${host}" \
"${port}" \
"${superuser}" \
"${user}" \
"--createdb" \
"--echo" \
"--inherit" \
"--login" \
"--no-createrole" \
"--no-replication" \
"--no-superuser"; then
exit 1
fi
}

function test_dropdb() {
local database="$1"
local user="$2"

local host="localhost"
local port=5432

if ! run_dropdb \
"false" \
"${host}" \
"${port}" \
"${user}" \
"${database}" \
"--if-exists" \
"--no-password"; then
exit 1
fi
}

function test_dropuser() {
local user="$1"
local host="localhost"
local port=5432
local superuser="root"
if ! run_dropuser \
"false" \
"${host}" \
"${port}" \
"${superuser}" \
"${user}" \
"--echo" \
"--if-exists"; then
exit 1
fi
}

function test_pg_dump() {
local database="$1"
local user="$2"

local host="localhost"
local port=5432

if ! run_pg_dump \
"false" \
"${host}" \
"${port}" \
"${user}" \
"${database}" \
"--compress=9" \
"--encoding=UTF-8" \
"--file=${HOME}/Desktop/${database}" \
"--format=directory" \
"--jobs=9" \
"--no-acl"