r_bash – Telegram
files after transfer"
AFTER_FILES=$(find "$LOCAL_DIR" -type f -name "*" 2>/dev/null | sort)
AFTER_COUNT=$(echo "$AFTER_FILES" | wc -l)
log_message "DEBUG: Files after transfer: $AFTER_COUNT"

# Determine if new files were transferred by comparing counts
if [ $AFTER_COUNT -gt $BEFORE_COUNT ]; then
NEW_FILES_COUNT=$((AFTER_COUNT - BEFORE_COUNT))
log_message "Transferred $NEW_FILES_COUNT new files to $LOCAL_DIR"

# Identify which files are new by comparing before and after
NEW_FILES=$(comm -13 <(echo "$BEFORE_FILES") <(echo "$AFTER_FILES"))
log_message "DEBUG: Newly detected files:"
EMAIL_CONTENT="${EMAIL_CONTENT}DEBUG: Newly detected files:
$NEW_FILES
"

# List the transferred files if any
if [ -n "$TRANSFERRED_FILES" ]; then
log_message "Files transferred:"
EMAIL_CONTENT="${EMAIL_CONTENT}--- Files Transferred ---
$TRANSFERRED_FILES
"
fi

# Success subject with timestamp
EMAIL_SUBJECT="[SFTP-SYNC] Transfer Complete - $(date '+%Y-%m-%d %H:%M') - $NEW_FILES_COUNT Files"
else
log_message "No new files detected, nothing transferred"
# Info subject with timestamp
EMAIL_SUBJECT="[SFTP-SYNC] Completed - $(date '+%Y-%m-%d %H:%M') - No Changes"

# Additional debugging if no files detected
log_message "DEBUG: Checking if files exist on remote server"
REMOTE_LS=$(echo "$SFTP_OUTPUT" | grep -A 100 "sftp>" | grep -v "sftp>")
EMAIL_CONTENT="${EMAIL_CONTENT}DEBUG: Remote directory listing:
$REMOTE_LS
"
fi

# Get list of all files in destination
log_message "Total files in destination directory: $AFTER_COUNT"
FILE_LIST=$(ls -la "$LOCAL_DIR" 2>/dev/null || echo "Cannot list directory contents")
EMAIL_CONTENT="${EMAIL_CONTENT}--- Directory Contents ---
${FILE_LIST}
"
else
log_message "WARNING: Local directory no longer exists after transfer"
fi

# Email subject for success
EMAIL_SUBJECT="[SUCCESS] SFTP File Transfer Complete"
else
log_message "ERROR: SFTP connection or file transfer failed with status $SFTP_STATUS"

# Email subject for failure
EMAIL_SUBJECT="[FAILED] SFTP File Transfer Error"
fi

# Clean up the temporary batch file
rm -f "$BATCH_FILE" 2>/dev/null
log_message "SFTP sync process completed"

# Create a temporary file for the email content
EMAIL_FILE=$(mktemp)
if [ $? -eq 0 ]; then
# Write email content to file
echo "$EMAIL_CONTENT" > "$EMAIL_FILE"

# Send email with content-type explicitly set to text/plain
(
echo "To: ${EMAIL_TO}"
echo "Subject: ${EMAIL_SUBJECT}"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=utf-8"
echo "Content-Transfer-Encoding: 8bit"
echo ""
cat "$EMAIL_FILE"
) | /usr/sbin/sendmail -t

# Remove temporary email file
rm -f "$EMAIL_FILE"
else
# Fallback to regular mail if temp file creation fails
echo "$EMAIL_CONTENT" | mail -s "${EMAIL_SUBJECT}" "${EMAIL_TO}"
fi

# Output completion message to console
echo "SFTP sync completed. Notification sent to ${EMAIL_TO}"

Apologies for the formatting ahead of time. I dont usually post, if someone could tell me what shortcut to use to format it properly would be appreciated.

Code is garbage, I’m sure, but i am not an expert by any means - Essentally what i am trying to accomplish, is to pull down files from a remote server via sftp. Running this noscript, it does it, but for some reason , when i try to add logic for the notifications, via email to update up when there are no changes, email subject should read - no changes - but whenever i add a file, it shows it and still runs a. The batch job process and pulls the file, but it keeps spitting out “changes” no matter if there is a change..e.x a file added…I can’t
tell if its my shitty code or something which is an underlying issue - open to feedback :)

https://redd.it/1j3ncpj
@r_bash
A process I'm trying to pipe data into using a named pipe reports a "Read error"

Hello everyone!! So I've been trying for the last hour and a half to get the "fftest" process to receive the input "0", so it would run its part of the program. It used to work, but after a couple of attempts and deleting the named pipe file it just stopped working.

The problematic code is this:

#!/bin/bash

loop(){
while [ 1 ]
do
sleep 2
echo 0 > pipef
sleep 18
done
}

mkfifo pipef
cat > pipef &
mypid=$!

trap "pkill -f fftest" SIGINT

loop &
looppid=$!
fftest /dev/input/by-id/usb-MediaTekInc.XBOXACC000000000-event-joystick < pipef

kill $mypid
kill $looppid
rm pipef

I'm creating the loop function that's responsible for the data input, then I open the pipe, then I run the loop, so it would pipe its data when the time comes and then I run the "fftest" command itself. The moment that command is ran it exits, reporting a "Read error".

This code used to work before, until it randomly stopped (that's why I created the new one in an attempt to fix it):

#!/bin/bash

mkfifo pipef
cat > pipef &
mypid=$!

fftest /dev/input/by-id/usb-MediaTekInc.XBOXACC000000000-event-joystick < pipef &
sleep 2
while [ 1 ]
do
echo 0 > pipef
sleep 20
done

kill $mypid
rm pipef

If you have found my mistake, please tell me!! Thank you so so much in advance!!! <3

Edit: This is the output with set -x:

+ mkfifo pipef
+ mypid=31874
+ trap 'pkill -f fftest' SIGINT
+ cat
+ looppid=31875
+ fftest /dev/input/by-id/usb-MediaTekInc.XBOXACC000000000-event-joystick
+ loop
+ [ -n 1 ]
+ sleep 2
Force feedback test program.
HOLD FIRMLY YOUR WHEEL OR JOYSTICK TO PREVENT DAMAGES

Device /dev/input/by-id/usb-MediaTekInc.XBOXACC000000000-event-joystick opened
Features:
Absolute axes: X, Y, Z, RX, RY, RZ, Hat 0 X, Hat 0 Y,
[3F 00 03 00 00 00 00 00 ]
Relative axes:
00 00
Force feedback effects types: Periodic, Rumble, Gain,
Force feedback periodic effects: Square, Triangle, Sine,
[00 00 00 00 00 00 00 00 00 00 03 07 01 00 00 00 ]
Number of simultaneous effects: 16

Setting master gain to 75% ... OK
Uploading effect #0 (Periodic sinusoidal) ... OK (id 0)
Uploading effect #1 (Constant) ... Error: Invalid argument
Uploading effect #2 (Spring) ... Error: Invalid argument
Uploading effect #3 (Damper) ... Error: Invalid argument
Uploading effect #4 (Strong rumble, with heavy motor) ... OK (id 1)
Uploading effect #5 (Weak rumble, with light motor) ... OK (id 2)
Enter effect number, -1 to exit
Read error
Stopping effects
+ kill 31874
./start.sh: line 24: kill: (31874) - No such process
+ kill 31875
+ rm pipef

https://redd.it/1j45ksb
@r_bash
Problem with imgur upload noscript

The noscript 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 noscript: https://pastebin.com/5SunZpkk

https://redd.it/1j4t512
@r_bash
> def (an sdcv dictionary reference tool for CLI)
https://redd.it/1j55sm1
@r_bash
I've created windows switcher

I created something handy today and I would like to share it and maybe get your opinion/suggestion. I've created window switcher noscripts that mapped to Ubuntu custom shortcut keys. When triggered it instantly finds the intended windows and switch to it no matter where you are in the workspace (reduces the need for constant alt+tab). This minimizes time and effort to navigate if you have many windows and workspace on. It uses wmctrl tool

I've created so far four switchers: terminal switcher, firefox switcher, google-chatgpt switcher, youtube switcher since these are my primary window cycles

[ubuntu keyboard custom shortcuts setting](https://preview.redd.it/3xkjyctq11ne1.png?width=515&format=png&auto=webp&s=d15a68225b5afefa4bc84b64ed40bfd2b3f40e61)

//terminal\_sw.sh (switch to your terminal. I keep all terminals in one workspace)

#!/bin/bash
wmctrl -a ubuntu <your_username>@ubuntu:~

//google\_sw.sh (it actually is a chatgpt switcher on google browser. The only way i know how to do chatgpt switcher)

#!/bin/bash
wmctrl -a Google Chrome

//firefox\_sw.sh (targeted firefox browser, need to explicitly exclude "YouTube" window to avoid conflating with youtube-only window)

#!/bin/bash
# Find a Firefox window that does not contain "YouTube"
window_id=$(wmctrl -lx | grep "Mozilla Firefox" | grep -v "YouTube" | awk '{print $1}' | head -n 1)
if [ -n "$window_id" ]; then
wmctrl -ia "$window_id"
else
echo "No matching Firefox window found."
fi

//youtube\_sw.sh (targeted firefox with youtube-only window)

#!/bin/bash
# Find a Firefox window that contains "YouTube"
window_id=$(wmctrl -lx | grep "YouTube — Mozilla Firefox" | awk '{print $1}' | head -n 1)
if [ -n "$window_id" ]; then
wmctrl -ia "$window_id"
else
echo "No YouTube window found."
fi

https://redd.it/1j4qy4v
@r_bash
New to bash, had a question about weird command substitution case

I've been taking an introduction to Linux and Bash course at my college and we came across this case when using echo and command substitution with variables. I thought that it would actually print the random number, but no matter how many echo $() I put, it always prints $RANDOM

export META='$RANDOM'

echo $(echo $(echo $META))

Can someone help me understand this interaction? Thank you

https://redd.it/1j4fz6t
@r_bash
how to make my bash noscript take lesser ram?

So, I wrote a bash noscript 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?

https://redd.it/1j5fe56
@r_bash
Tar2Deb

Pure bash noscript that converts a tar file into a deb file

in order to install tar2deb you need wget, note only works for debian based distros.

features

automatically move images in the extracted tar directory that holds a subdirectory with the most images then export it as a variable then moves to the deb directory, the deb directory is needed in order to create a .deb file, it uses imagemagick to move each image by dimension, before the dimensions and after is extracts the tar file it will ask the user what does want the package name be, does not allow numbers except 2, then the name of the package the user chooses will be exported as a variable, then it will ask the user what is version of your package, once the user chosen its version for the package it will be exported as a variable then combine those to variables like this $PackageName-$Version then it will create the directory with those 2 variables then it will ask the user what name of the maintainer, whatever name the user decides will be exported as a variable, then it asks the user what is the package about, whatever the users type will also because exported as variable, then it will create the control file in the deb dir DEBIAN folder, then once the control file is created, it will create the directories in the deb directory, then it will find a graphical executable file (excluding binary files) and move to deb_dir/usr/bin after it does then it will go the dimensions after it moves the dimension it will ask the user a yes or no prompt asking if it wants to rename all image files moved into one name if the users say no then it will ask the user if it wants to rename a file from the numerical list and whatever numbers it chooses it will prompt the user what the name to be for the file then it combine that name with the file extension and renames the chosen file with the name that user choose, then it create a desktop if there is not an desktop file in the tar directory it will ask the user if it wants to create a desktop since there is not located in tar directory if the users say user then it do a prompt asking the user what executable file it wants to choose for desktop file then it will show a numerical list showing a list of images and whatever image the user chooses will be the icon of the desktop file once the desktop file is

how to install tar2deb

sudo apt install wget && wget https://github.com/GitXpresso/Tar2Deb/releases/download/v.1.0.0/tar2deb-1.0.0.deb && sudo apt install -y ./tar2deb-1.0.0.deb

https://redd.it/1j5u1xh
@r_bash
backup copy of .bashrc for the root directory?

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

https://redd.it/1j6v9l7
@r_bash
Command completion suggestions while typing?

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.

https://redd.it/1j6o5zg
@r_bash
HELP Please. The while loop is running before SSH has ended completely.

https://preview.redd.it/6yv2drjx0ine1.png?width=687&format=png&auto=webp&s=afaef25c281cf083cbc5685e7552203ef6375e58

https://preview.redd.it/f622kvze1ine1.png?width=596&format=png&auto=webp&s=943b60670c3d4ce0e63d5e143673302c5db97f08

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?

https://redd.it/1j6lxab
@r_bash
In theory, could all quoting be achieved with just the backlash character? Or are there instances where single quotes are required

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

https://redd.it/1j7jak3
@r_bash
exitcode from a pipe inside an if statement

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 noscript 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.

https://redd.it/1j7q8as
@r_bash
New to Bash Scripting and Sysadmin? Check Out My Tool: Linux Console Manager (Open Source - All Feedback Appreciated)

Hi r/bash community!

I'm a new Redditor, and I wanted to share a simple bash noscript 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 noscript 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 noscript.
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 noscript 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 noscript is completely open source and available on GitHub: https://github.com/forsys02/linux\_console\_manager

https://preview.redd.it/1avm3lnnsune1.png?width=458&format=png&auto=webp&s=25a753e1bb074cbc0dbd4e8f4a93c8caa952de5f

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 noscripting! 😊



https://redd.it/1j7x3vj
@r_bash
i want to put raw code into a variable by utilizing heredoc, but it seems that the outer syntax is interpreting things

what i'm trying to do is make a noscript 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?

https://redd.it/1j8q85k
@r_bash