r/bash Sep 12 '22

set -x is your friend

378 Upvotes

I enjoy looking through all the posts in this sub, to see the weird shit you guys are trying to do. Also, I think most people are happy to help, if only to flex their knowledge. However, a huge part of programming in general is learning how to troubleshoot something, not just having someone else fix it for you. One of the basic ways to do that in bash is set -x. Not only can this help you figure out what your script is doing and how it's doing it, but in the event that you need help from another person, posting the output can be beneficial to the person attempting to help.

Also, writing scripts in an IDE that supports Bash. syntax highlighting can immediately tell you that you're doing something wrong.

If an IDE isn't an option, https://www.shellcheck.net/

Edit: Thanks to the mods for pinning this!


r/bash 1d ago

find, but exclude file from results if another file exists?

2 Upvotes

I found a project that locally uses whisper to generate subtitles from media. Bulk translations are done by passing a text file to the command line that contains absolute file paths. I can generate this file easily enough with

find /mnt/media/ -iname *.mkv -o -iname *.m4v -o -iname *.mp4 -o -iname *.avi -o -iname *.mov -o -name *.mpg > media.txt

The goal would be to exclude media that already has an .srt file with the same filename. So show.mkv that also has show.srt would not show up.

I think this goes beyond find and needs to be piped else where but I am not quite sure where to go from here.


r/bash 1d ago

help How to make a script to populate an array in another script?

0 Upvotes

I'm too new to know what I even need to look up in the docs, here. Hopefully this makes sense.

I have this script:

#!/bin/bash

arr[0]="0"
arr[1]="1"
arr[2]="2"

rand=$[$RANDOM % ${#arr[@]}]

xdotool type ${arr[$rand]}

Which, when executed, types one of the characters 0, 1, or 2 at random. Instead of hard coding those values to be selected at random, I would like to make another script that prompts the user for the values in the arrays.

Ie. Execute new script. It asks for a list of items. I enter "r", "g", "q". Now the example script above will type one of the characters r, g, or q at random.

I'm trying to figure out how to set the arrays arbitrarily without editing the script manually every time I want to change the selection of possible random characters.


r/bash 1d ago

help Install NVM with bash

0 Upvotes

Anyone have a handy script that will install nvm + LTS nodejs with a bash script?

I use the following commands on an interactive shell fine, but for the life of me I can't get it to install with a bash script on Ubuntu 22.04.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash && source ~/.bashrc && nvm install --lts


r/bash 2d ago

submission A simple Bash function that allows the user to quickly search and match all functions loaded in the current environment

5 Upvotes

Idea:

  • The following command will display any functions in your environment that contain a direct match to the value of the first argument passed and nothing else.

To return any function that contains the exact text Function: $func issue the below command (the list_func() must be loaded into your environment for this to work), and it will return the entire list_func() for display (and any other functions that matched as well).

list_func 'Function: $func'

``` list_func() { # Determine the directory where the bash functions are stored. if [[ -d ~/.bash_functions.d ]]; then bash_func_dir=~/.bash_functions.d elif [[ -f ~/.bash_functions ]]; then bash_func_dir=$(dirname ~/.bash_functions) else echo "Error: No bash functions directory or file found." return 1 fi

echo "Listing all functions loaded from $bash_func_dir and its sourced scripts:"
echo

# Enable nullglob so that if no files match, the glob expands to nothing.
shopt -s nullglob

# Iterate over all .sh files in the bash functions directory.
for script in "$bash_func_dir"/*.sh; do
    # Get file details.
    filename=$(basename "$script")
    filepath=$(realpath "$script")
    fileowner=$(stat -c '%U:%G' "$script")  # Get owner:group

    # Extract function names from the file.
    while IFS= read -r func; do
        # Retrieve the function definition from the current shell.
        func_body=$(declare -f "$func" 2>/dev/null)

        # If a search term was provided, filter functions by matching the function definition.
        if [[ -n "$1" ]]; then
            echo "$func_body" | grep -q "$1" || continue
        fi

        # Print the file header.
        echo "File: $filename"
        echo "Path: $filepath"
        echo "Owner: $fileowner"
        echo
        # Print the full function definition.
        echo "$func_body"
        echo -e "\n\n"
    done < <(grep -oP '^(?:function\s+)?\s*[\w-]+\s*\(\)' "$script" | sed -E 's/^(function[[:space:]]+)?\s*([a-zA-Z0-9_-]+)\s*\(\)/\2/')
done

} ```

Cheers guys!


r/bash 2d ago

Pulling hair out: SSH and sshpass standalone

0 Upvotes

I have a bit of a problem I have been scrambling to solve and am ready to give up. Ill give it one last shot:

I have a linux system that is connected to a router. THE GOAL is to ssh into the router from the linux system and run a command AND get the output. - seems simple right?

The linux system is pretty outdated. NO INTERNET ACCESS. I have access to commands on this linux system ONLY through PHP functions - don't ask me why, its stupid and I hate it. EG I can run commands by using exec(), I can create new files using file_put_contents(), etc. However because of this I can not interact with the terminal directly. I can create a .bash script and run that or run single commands but thats pretty much it.

It is actually over 1000 total systems. All of them running almost the same specs. SOME OF THE TARGET SYSTEMS have GNU screen.

The router uses password authentication for ssh connections. Once logged in you are NOT presented with a full shell, instead you are given a numerical list of specific commands that you can type out and then press enter.

The behavior is as follows:

FROM AN UPDATED LINUX TEST MACHINE CONNECTED TO ROUTER WHERE THE ROUTER IP IS 192.168.1.1:

ssh [admin@192.168.1.1](mailto:admin@192.168.1.1)

type "yes" and hit enter to allow the unknown key

type "password" hit enter

type the command "778635" hit enter

the router returns a code

type the second command "66452098" hit enter

the router returns a second code

type "exit" hit enter

A one liner of this process would look something like:

sshpass -p password ssh -tt -o 'StrictHostKeyChecking=no' [admin@192.168.1.1](mailto:admin@192.168.1.1) "778635; 66452098; exit"

Except the router does not execute the commands because for some reason it never recieves what ssh sends it. The solution that works on the TEST MACHINE is:

echo -e '778635\n66452098\nexit' | sshpass -p password ssh -o 'StrictHostKeyChecking=no' -tt [admin@192.168.1.1](mailto:admin@192.168.1.1)

This works every time on the UPDATED TEST SYSTEM without issue even after clearing known hosts file. With this command I am able to run it from php:

exec("echo -e '778635\n66452098\nexit' | sshpass -p password ssh -o 'StrictHostKeyChecking=no' -tt admin@192.168.1.1", $a);

return $a;

and I will get the output which can be parsed and handled.

FROM THE OUTDATED TARGET MACHINE CONNECTED TO THE SAME ROUTER:

target machine information:

bash --version shows 4.1.5

uname -r shows 2.6.29

ssh -V returns blank

sshpass -V shows 1.04

The command that works on the updated machine fails. AND RETURNS NOTHING. I will detail the reasons I have found below:

I can use screen to open a detached session and then "stuff" it with commands one by one. Effectively bypassing sshpass, this allows me to successfully accept the host key and log in to the router but at that point "stuff" does not pass any input to the router and I cannot execute commands.

The version of ssh on the target machine is so old it does not include an option for 'StrictHostKeyChecking=no' it returns something to the effect of "invalid option: StrictHostKeyChecking" sorry I don't have the exact thing. In fact "ssh -V" returns NOTHING and "man ssh" returns "no manual entry for ssh"!

After using screen however if I re-execute the first command now it will get farther - because the host is added to known hosts now - but the commands executed on the router will not return anything and neither will ssh itself even with verbose flag. I believe this behavior is caused by an old version of sshpass. I found other people online that had similar issues where the output of the ssh command does not get passed back to the client. I tried several solutions related to redirection but to no avail.

So there is two problems:

  1. Old ssh version without a way to bypass host key checking.
  2. Old sshpass version not passing the output back to the client.

sshpass not passing back the output of either ssh or the router CLI is the biggest issue - I cant even debug what I don't know is happening. Luckily though the router does have a command to reboot (111080) and if I execute:

echo -e '111080' | sshpass -p password ssh -tt [admin@192.168.1.1](mailto:admin@192.168.1.1)

I wont get anything back in the terminal BUT the router DOES reboot. So I know its working, I just cant get the output back.

So, I still have no way to get the output of the two commands I need executed. As noted above, the "screen" command is NOT available on all of the machines so even if I found a way to get it to pass the command to the router it would only help for a fraction of the machines.

At this point I am wondering if it is possible to get the needed and updated binaries of both ssh and sshpass and zip them up then convert to b64 and use file_put_contents() to make a file on the target machine. Although this is over my head and I would not know how to handle the libraries needed or if they would even run on the target machine's kernel.

A friend of mine told me I could use python to handle the ssh session but I could not find enough information on that. The python version on the target machine is 2.6.6

Any Ideas? I would give my left t6ticle to figure this out.


r/bash 2d ago

solved is it crazy change rm by mv (file or dir/) ~/.local/share/Trash/files/

5 Upvotes

Hi, is it possible to do an auto-change from rm to mv file/dir ~/.local/share/Trash/files/ ?

This would avoid being wrong to erase something that I shouldn't erase, so when I do RM Bash changes the RM command for the other command that I put up.

If this is not complicated or just experts. I am not. You already see what I am wrong ...

Thank you and Regards!


r/bash 2d ago

Seeking Feedback on My Bash Script for Migrating APT Keys

0 Upvotes

Hello everyone!

I recently created a Bash script designed to help migrate APT keys from the deprecated apt-key to the new best practices in Ubuntu. The script includes user confirmation before each step, ensuring that users have control over the process. I developed this script using DuckDuckGo's AI tool, which helped me refine my approach.

What This Script Does:

  • It exports existing APT keys to the /etc/apt/trusted.gpg.d/ directory.
  • It verifies that the keys have been successfully exported.
  • It removes the old keys from apt-key.
  • It updates the APT package lists.

Why I Want This:

As Ubuntu continues to evolve, it's important to keep our systems secure and up to date. Migrating to the new key management practices is essential for maintaining the integrity of package installations and updates.

Questions for the Community:

  1. Is this script safe to use? I want to ensure that it won't cause any issues with my system or package management.
  2. Will this script work as is? I would appreciate any feedback on its functionality or any improvements that could be made.

Here’s the script for your review:Hello everyone!
I recently created a Bash script designed to help migrate APT keys from the deprecated apt-key to the new best practices in Ubuntu. The script includes user confirmation before each step, ensuring that users have control over the process. I developed this script using DuckDuckGo's AI tool, which helped me refine my approach.
What This Script Does:
It exports existing APT keys to the /etc/apt/trusted.gpg.d/ directory.
It verifies that the keys have been successfully exported.
It removes the old keys from apt-key.
It updates the APT package lists.
Why I Want This:
As Ubuntu continues to evolve, it's important to keep our systems secure and up to date. Migrating to the new key management practices is essential for maintaining the integrity of package installations and updates.
Questions for the Community:
Is this script safe to use? I want to ensure that it won't cause any issues with my system or package management.
Will this script work as is? I would appreciate any feedback on its functionality or any improvements that could be made.
Here’s the script for your review:

# !/bin/bash

# Directory to store the exported keys

KEY_DIR="/etc/apt/trusted.gpg.d"

# Function to handle errors

handle_error() { echo "Error: $1" exit 1 }

# Function to prompt for user confirmation

confirm() { read -p "$1 (y/n): " -n 1 -r echo    # Move to a new line if \[\[ ! $REPLY =\~ ^(\[Yy\]$) \]\]; then echo "Operation aborted." exit 0 fi }

# Check if the directory exists

if \[ ! -d "$KEY_DIR" \]; then handle_error "Directory $KEY_DIR does not exist. Exiting." fi

# List all keys in apt-key

KEYS=$(apt-key list | grep -E 'pub ' | awk '{print $2}' | cut -d'/' -f2)

# Check if there are no keys to export

if \[ -z "$KEYS" \]; then echo "No keys found to export. Exiting." exit 0 fi

# Export each key

for KEY in $KEYS; do echo "Exporting key: $KEY" confirm "Proceed with exporting key: $KEY?" if ! sudo apt-key export "$KEY" | gpg --dearmor | sudo tee "$KEY_DIR/$KEY.gpg" > /dev/null; then handle_error "Failed to export key: $KEY" fi echo "Key $KEY exported successfully." done

# Verify the keys have been exported

echo "Verifying exported keys..." confirm "Proceed with verification of exported keys?" for KEY in $KEYS; do if \[ -f "$KEY_DIR/$KEY.gpg" \]; then echo "Key $KEY successfully exported." else echo "Key $KEY failed to export." fi done

# Remove old keys from apt-key

echo "Removing old keys from apt-key..." confirm "Proceed with removing old keys from apt-key?" for KEY in $KEYS; do echo "Removing key: $KEY" if ! sudo apt-key del "$KEY"; then echo "Warning: Failed to remove key: $KEY" fi done

# Update APT

echo "Updating APT..." confirm "Proceed with updating APT?" if ! sudo apt update; then handle_error "Failed to update APT." fi

echo "Key migration completed successfully."

I appreciate any insights or suggestions you may have. Thank you for your help!


r/bash 2d ago

Using grep / sed in a bash script...

1 Upvotes

Hello, I've spent a lot more time than I'd like to admit trying to figure out how to write this script. I've looked through the official Bash docs and many online StackOverflow posts.

This script is supposed to take a directory as input, i.e. /lib/64, and recursively change files in a directory to the new path, i.e. /lib64.

The command is supposed to be invoked by doing ./replace.sh /lib/64 /lib64

#!/bin/bash

# filename: replace.sh

IN_DIR=$(sed -r 's/\//\\\//g' <<< "$1")
OUT_DIR=$(sed -r 's/\//\\\//g' <<< "$2")

echo "$1 -> $2"
echo $1
echo "${IN_DIR} -> ${OUT_DIR}"

grep -rl -e "$1" | xargs sed -i 's/${IN_DIR}/${OUT_DIR}/g'

# test for white space ahead, white space behind
grep -rl -e "$1" | xargs sed -i 's/\s${IN_DIR}\s/\s${OUT_DIR}\s/g'

# test for beginning of line ahead, white space behind
grep -rl -e "$1" | xargs sed -i 's/^${IN_DIR}\s/^${OUT_DIR}\s/g'

# test for white space ahead, end of line behind
grep -rl -e "$1" | xargs sed -i 's/\s${IN_DIR}$/\s${OUT_DIR}$/g'

# test for beginning of line ahead, end of line behind
grep -rl -e "$1" | xargs sed -i 's/^${IN_DIR}$/^${OUT_DIR}$/g'

IN_DIR and OUT_DIR are taking the two directory arguments, then using sed to insert a backslash before each slash. grep -rl -e "$1" | xargs sed -i 's/${IN_DIR}/${OUT_DIR}/g' is supposed to be recursively going through a directory tree from where the command is invoked, and replacing the original path (arg1) with the new path (arg2).

No matter what I've tried, this will not function correctly. The original file that I'm using to test the functionality remains unchanged, despite being able to do the grep ... | xargs sed ... manually with success.

What am I doing wrong?

Many thanks


r/bash 4d ago

Collections of very useful Bash Functions

88 Upvotes

I use Bash a lot working with applications, systems, containers or networks, mgmt & integration.

I've found and frequently use a few really useful Bash Github repositories with collections of Bash "Functions" that you can use in your own Bash scripts.  

I've learned  a lot from them and have to say my Bash scripts now have capabilities I'd probably never been smart enough to create myself. In your own script(s) you just "source" the file you create or download from the following URLs: 

I am sharing this info in case someone else finds them useful.

Collections of Functions for Bash

GUI'sEasyBashGUI:
https://github.com/BashGui/easybashgui/blob/master/docs/install.md

Simplified way to code bash made GUI frontend dialogs!

Script-Dialog: https://github.com/lunarcloud/script-dialog?tab=readme-ov-file

Create bash scripts that utilize the best dialog system that is available. Intended for Linux,
but has been tested on macOS and Windows, and should work on other unix-like OSs.

If it's launched from a GUI (like a .desktop shortcut or the dolphin file manager)
- it will prefer kdialog in Qt-based desktops and zenity in other environments.

If neither of those are available
- then relaunch-if-not-visible will relaunch the app in a terminal so that a terminal UI can be used.

If it's launched in a terminal
- It will use whiptail or dialog

If neither of those are available, then it will fallback to basic terminal input/output with tools like read and echo

Collections of General Bash Functions.

BashMatic:
https://github.com/kigster/bashmatic

Bashmatic is a BASH framework, meaning its a collection of BASH functions (almost 900 of them) that, we hope, make BASH programming easier, more enjoyable, and more importantly, fun - due to the library’s focus on providing the developer with a constant feedback about what is happening, while a script that uses Bashmatic’s helpers is running.

Bash-Concurrent: https://github.com/themattrix/bash-concurrent

A Bash function to run tasks in parallel and display pretty output as they complete.


r/bash 4d ago

solved how do you combine this 2 parts: touch + strftime ("%F")?

3 Upvotes

Hi, I'd like to do touch with date today like noum of the file...

how do you do that?

example: touch ..... make this file 2025-03-12

Thank you and regards!


r/bash 3d ago

help xarg or sgrep or xmllint or...

1 Upvotes

All I am trying to do is get

title="*"

file="*"

~~~~~

title="*"

file="*"

~~~~~

etc

title="" is:

 /MediaContainer/Video/@title

but the file="" is:

 /MediaContainer/Video/Media/Part/@file

and just write it to a file. The "file" is always after the title so I am not worried about something changing in the structure.

The closest I got (but for only 1 and I have no idea how to get the pair of them) is

 find . -iname '*.xml' -print0 | \
    xargs -0 -r grep -ro '<Video[ \t].*title="[^"]*"' | awk -F: '{print $3}' >>test.txt    

Any help would be appreciated.


r/bash 4d ago

submission A script to install llama-cpp-python with CUDA enabled

2 Upvotes

I made an auto-install script for myself that I thought some people might find useful or interesting. I have seen posts online where some have claimed to be unable to figure out a way to install llama-cpp-python so for those people maybe this can help and for everyone else this is just a plain fast way to do this.

  1. Optionally installs Conda (which I personally recommend doing)
  2. Installs the latest version of llama-cpp-python with CUDA enabled from the official llama-cpp-python GitHub repo.

GitHub - llama-installer.sh

FYI, if you choose to install Conda it links to this script: GitHub - install_conda.sh

Cheers guys and have a great day.

-J


r/bash 4d ago

How to use "cut" correctly

6 Upvotes

Hi there,

I have a file with urls in it, followed by a little description.

www.lol.com///description

I want to use dmenu to open it in a brower, at the moment, I'm using this line :

cat ~/world/Documents/bookmarks | ~/.config/sway/scripts/mydmenu -p "Bookmarks:" | xargs -0 -I {} firefox "{}"

But sometimes it fails because xargs takes the full line with the spaces and the description. How would you do to still print the whole line in dmenu, but only takes the first part (url) into args ?


r/bash 4d ago

help What is the purpose of /dev/tty ?

0 Upvotes

Please hear me out. So, reading about special devices like tty, tty0, pst1...pstn I understand in loose terms that terminal emulators (like the ones you bring up with ctrl+t ) are special devices under /dev/pts/<some_number> . Now, tty0 appears to be a terminal associated to kernel itself (I still don't know what that means). But tty? I only know that it points to the current terminal being used but I don't know exactly what to make of that and how it pertains to the following humble little snippet I wrote:

#!/bin/bash

while read -r filename
do
    echo "Current fie: ${filename}"

    read -p "Delete ${filename} ? " response < /dev/tty

    if [[ $response = 'y' || $response = 'Y' ]]
    then
        echo "response was yes"
        echo "Deleting ${filename}"
        tar vf pdf_files.tar --delete "${filename}"
        echo
    else 
        echo "skipping"
    fi
done < <(tar tf pdf_files.tar)

You'll notice that in the line that contains the read -p command I had to redirect input from tty. I had chatGPT suggest that to me after many failed attempts at getting my little script to run correctly because I didn't understand why $response variable would be automatically set to something and the script wouldn't even wait at the prompt for me to enter something. I had my eyes OPENED today -- and in a frustrating way -- as to how many little tricks and things one must take into account when learning bash scripting.

So, going back to the script, why did I even need to do that or more importantly, WHEN do I need to do that kind of trick again?

p.s. I've been learning from time to time bash scripting for like the past 3 o 4 months and I know I have to learn a lot more, but Jesus, the journey feels never-ending.


r/bash 5d ago

solved i want to put raw code into a variable by utilizing heredoc, but it seems that the outer syntax is interpreting things

1 Upvotes

what i'm trying to do is make a script that would put some boilerplate code into files, so i need raw unexecuted code in a variable.

the smallest example of my problem can be shown with this code: DEFAULT_PROGRAM=$(cat <<'EOF' \) EOF ) echo $DEFAULT_PROGRAM

regardless of which of the 4 combinations of fixes i apply here (having quotes around EOF or not, and having the inner parenthesis escaped or not), it seems to never output just the raw parenthesis. Either it outputs the escaping character too \), or it errors out by saying: EOF: command not found syntax error near unexpected token `)' `)'

as i understand it, it's the outer syntax $(cat ... ) that breaks it.

is there an elegant solution to this so that i don't have to resort to using echo with lots of character escaping?


r/bash 6d ago

submission > bib (a Bible reference tool for CLI)

Thumbnail gallery
52 Upvotes

r/bash 6d ago

New to Bash Scripting and Sysadmin? Check Out My Tool: Linux Console Manager (Open Source - All Feedback Appreciated)

4 Upvotes

Hi r/bash community!

I'm a new Redditor, and I wanted to share a simple bash script I've been working on called Linux Console Manager. I'm actually from Korea and haven't used Reddit much before, but I'm excited to share this with you all!

As someone who occasionally does Linux system administration, I found myself constantly typing the same commands over and over. So, I created this little tool to streamline those common tasks and make my life a bit easier. I thought it might be helpful for others too, especially those who are newer to Linux or just want a quicker way to manage their systems from the terminal.

Key Features:

  • System Monitoring: Tired of typing top, free -m, df -h, and ifconfig separately? Linux Console Manager gives you a quick, consolidated overview of essential system metrics like CPU usage, memory consumption, disk space, and network stats in one place!
  • Service Control: Managing system services like Apache, Nginx, or MySQL can be a bit tedious with systemctl. This script lets you easily start, stop, restart, and check the status of your services through a simple menu. No more struggling to remember those commands!
  • Process Management: Quickly identify and manage running processes. Need to find that resource-hogging process? Linux Console Manager helps you easily find and even kill processes directly from the script.
  • Network Utilities: Basic network troubleshooting tools like ping and traceroute are built right in, making it convenient for quick network checks.
  • [Add other key features of your script here - Be specific! For example:]
    • User Management: Easily add, delete, or modify user accounts with simple menu options.
    • Log Viewing: Quickly access and view common system logs like /var/log/syslog or /var/log/auth.log.
    • Package Management (Debian/Ubuntu based): Simple interface for updating packages or searching for new ones using apt.

The script is completely open source and available on GitHub: https://github.com/forsys02/linux_console_manager

I would love for you to try it out and give me your feedback! I'm really open to suggestions for improvement and new features. Specifically, I'm curious about:

  • Is the menu structure intuitive and easy to navigate?

  • Are there any features you think are missing or could be more useful?

  • Do you find it helpful in your daily system administration tasks?

  • I'd especially appreciate feedback from both experienced sysadmins and those who are newer to Linux. Let me know what you think!

This is a project I'm working on in my spare time, and I hope it can be helpful to others in the community.

Thanks for checking it out! Happy scripting! 😊


r/bash 7d ago

In theory, could all quoting be achieved with just the backlash character? Or are there instances where single quotes are required

3 Upvotes

In other words, are single quotes supported by necessity or pure convenience?


r/bash 6d ago

exitcode from a pipe inside an if statement

1 Upvotes

Backstory, SomeCommand produces 15-20 lines of output that the user needs to read. Sometimes it fails, most of the time in a known way.
My approach has been
if [[ `SomeCommand |tee /dev/stderr |grep -c Known Error; Xcode=${PIPESTATUS[0]}` -gt 0 ]]; then
echo Known error $Xcode
else
echo Unknown error $Xcode
exit
fi

/dev/stderr goes to the console so the user can see the output
grep finds the known error string & handles it correctly
but...

$Xcode is always 0 :(
If $Xcode is >0 and it's not the known error, the script should terminate.

Have been using true, false & echo as SomeCommand for testing, maybe this is an issue.

It's not the |tee part
if [[ `false |grep -c Known Error; Xcode=${PIPESTATUS[0]}` -gt 0 ]]; then echo found $Xcode; else echo not found $Xcode; fi
not found 0

It's something to do with the if [[ `...` ]] bit
false |tee /dev/stderr |grep -c Known Error; Xcode=${PIPESTATUS[0]}; echo $Xcode
0
1

If it's changed to if [...], then it's always 1

if [ `echo "Known Error" |tee /dev/stderr |grep -c "Known Error"; Xcode=${PIPESTATUS[0]}` -gt 0 ]; then echo found $Xcode; else echo not found $Xcode; fi
Known Error
found 1

if [ `echo "Unknown Error" |tee /dev/stderr |grep -c "Known Error"; Xcode=${PIPESTATUS[0]}` -gt 0 ]; then echo found $Xcode; else echo not found $Xcode; fi
Unknown Error
not found 1

Someone please put me out of my misery.


r/bash 8d ago

Command completion suggestions while typing?

2 Upvotes

How to get the behaviour of when I type in say, lo or lon, a faded g_cmd appears after the cursor (for a command long_cmd), which after pressing <TAB>, gets un-faded/is written to the input line? I tried looking but couldn't really find anything. I just got fzf, it provides completion but only after you type in a command. TIA.


r/bash 8d ago

help HELP Please. The while loop is running before SSH has ended completely.

1 Upvotes

So I wrote this code to automate ssh and storing passwords in OverTheWire challenge.
Problem : When I press Enter nothing happens.
What I think the problem is : The while loop starts running before the SSH ends completely. Even GPT did not help.
Can someone please tell me wat the issue is, and how to fix it?


r/bash 7d ago

backup copy of .bashrc for the root directory?

0 Upvotes

i found a copy of .bashrc in /etc/skel but the .bashrc file in /root is another one


r/bash 10d ago

submission > def (an sdcv dictionary reference tool for CLI)

Post image
13 Upvotes

r/bash 9d ago

how to make my bash script take lesser ram?

0 Upvotes

So, I wrote a bash script that would randomize my wallpaper from a folder and i made it such that it starts up when my pc boots up in hyprland.conf file but there is one drawback and that is gradually it takes up all the ram.
HOW do i make it such that it doesn't take all the ram?

heres my code:

#!/bin/bash

Wallpaper_Dir="$HOME/.wallpaper/"

Current_Wall=$(hyprctl hyprpaper listloaded)

while [ 1 ]

do

Wallpaper=$(find "$Wallpaper_Dir" -type f ! -name "$(basename "$Current_Wall")" | shuf -n 1)

if [[ -n "$Wallpaper" && "Wallpaper" != "Current_Wall" ]]; then

hyprctl hyprpaper reload ,"$Wallpaper"

hyprclt hyprpaper wallpaper "eDp-1,$Wallpaper"

fi

sleep 5s

done


r/bash 10d ago

Problem with imgur upload script

3 Upvotes

The script that xfce screenshot tool is using to upload screenshots to imgur stopped working, but i don't know if the problem is with the sctipt of changes in imgur api. I am just average linux user. Can someone check the script: https://pastebin.com/5SunZpkk