r_bash – Telegram
using grep in noscript

I am trying to write a noscript that will list a directory's contents and use grep to filter for only certain match sub directories and files. While the grep command works in command line fine when I put it in a noscript it no longer gives a return just holds up the noscript causing me to have to Ctrl-C out of it. I'm now a brand new noscripting guy but definitely a novice. I am on a Linux Machine attempting this. Any assistance would be greatly appreciated.

https://redd.it/128otp8
@r_bash
Need assistance for bash noscript

I have a noscript i am writing which lists directories or files in a location and displays them as selections to choose from. Once Chosen I would like to copy the "file" or "directory" to a new locations keeping all the contents. The copy part is goofing me up I cant seem to figure out how as when I am listing the choices its saving the full directory path PLUS a ":" sign. All I need is the full path call out and then a way to copy to a new given location. This noscript is being written on a linux machine.

Following is what I have thus far.. its proving challenging but ive been working on this for 4 hours just to get this far... I know the final line does not work.

#!/bin/bash

echo "Please select the item from the list"

files=$(ls /home/mib2/WorkTest/20230331*)
i=1

for j in $files
do
echo "$i.$j"
file[i]=$j
i=$(( i + 1 ))
done

echo "Enter number to select"
read input
echo "You selected: ${file[$input]}"

cp -R "${file[$input]}" /home/mib2/WorkTest/WWW/NEW1/

https://redd.it/128tnm0
@r_bash
Writing a noscript that adds numbers to the end of a text file full of words

I am trying to write a noscript that adds numbers to the end of a list of words. Here's what I've tried:

#!/bin/bash
# add_numbers.sh

while read w; do
echo ${w}{0..9}
done

Then I run it with `$ ./add_numbers.sh < words.txt`

This runs, but it adds the numbers on the next line down, I think:

9 ZOOS
9 ZORN
9 ZOROASTER
9 ZOROASTRIAN

&#x200B;

So I tried to strip the carriage return (right?) at the end of the line when `read` gets the line:

#!/bin/bash
# add_numbers.sh

while read w; do
stripped=echo ${w} | tr -d "\r"
echo ${stripped}{0..9}
done

But the output just gives errors:

./add_numbers.sh: line 4: $'AGGLUTINATE\r': command not found
0 1 2 3 4 5 6 7 8 9
./add_numbers.sh: line 4: $'AGGLUTINATED\r': command not found

&#x200B;

What am I doing wrong?

&#x200B;

EDIT: For the heck of it I asked GPT3.5 to do this and here's what I got:


#!/bin/bash

while read line; do
for i in {0..9}; do
echo "$line$i"
done
done < "${1:-/dev/stdin}"

I left out the stdin redirect at the bottom, but what it outputs replaces the first character with a number in each word:

9ULU
0ULUS
1ULUS

Those lines would be ZULU and ZULUS.

https://redd.it/128y3cp
@r_bash
Noobie BASH help

Hi -

New to BASH noscripting and need some direction.
I have this noscript below, but it's not creating the file i'm after. I think its related to path name for the new file location.

The error i'm getting is:
Start time: Sun, 02 Apr 2023 15:05:17 GMT
Stop time: Sun, 02 Apr 2023 15:05:18 GMT
Current status: 0 (Normal)
Standard output/error:
/bin/bash: line 15: Scripts/test/20230402-150518.txt: No such file or directory
Text file created at: Scripts/test/20230402-150518.txt

But no file created. I think i have the path name wrong, but not sure how to format it?

I think this is wrong.... folder_path="/Scripts/test"
but i'm not sure "why" its wrong.

&#x200B;

Any help appreciated-


\~\~

\#!/bin/bash

\# Get the current date and time

datetime=$(date +"%Y%m%d-%H%M%S")

&#x200B;

\# Get the current day name and date

day_and_date=$(date +"%A, %B %d, %Y")

&#x200B;

\# Specify the folder where you want to create the text file

folder_path="/Scripts/test"

&#x200B;

\# Create the text file with the date time stamp as the file name

file_path="${folder_path}/${datetime}.txt"

&#x200B;

\# Write the day name and date to the text file

echo "$day_and_date" > "$file_path"

&#x200B;

\# Print the file path for reference

echo "Text file created at: $file_path"

\~\~

https://redd.it/129b1l5
@r_bash
What constitutes a "debugger enabled version of bash"

Hello.

Just for the hell of it for now, but it may be useful in the future, to have a gdb-alike front end for debugging bash noscripts, I think it is more pleasant than just a DEBUG trap.

Right now, I'm getting feedback indicating that `bashdb` isn't installed, but I also get the message:

warning: cannot start debugger; debugging mode disabled

So, I'm in doubt whether it is:

* A special version of bash, built for supporting [bashdb](https://sourceforge.net/projects/bashdb/files/bashdb/).

* Having a properly installed version of bashdb.

* One of the above in combination with `shopt -s extdebug`.

And I won't take further action, before I understand what that means.

I haven't installed `bashdb` yet. I can't find a debugger enabled version of bash in the `apt` repository, so, I wonder if I ultimately have to build a debug-enabled bash version myself. :)


Thanks!

https://redd.it/129fc1g
@r_bash
How to differentiate between output and information in bash noscript

Sorry for the terrible noscript but I really couldn't think of anything better.

I have a bash noscript that uses echo to print some information about the execution context and then execute a command with said context.

I want to take the output of that command and save it into a variable or pipe it into another program.

The problem is that the contextual information is also considered as part of the output.

In PowerShell I can use Write-Host and Write-Output to differentiate the two.

Is there something similar in bash?

Example:

$ ./terraform.sh env output -raw some_value
Environment 'env' running on '<AWS region>'
a_very_useful_information


Obviously I want to save the output in a variable and be able to use it somewhere else without the information line printed before.

https://redd.it/129i3d7
@r_bash
bash behavior with nested parentheses?

Is there a (documented) reason why I can use for i in sd[abc]; do … , done and get correct values of sda, sdb, sdc, but I can't use for i in {sd[abc],mmcblk0}; do … , done because I only get sdaabc and mmcblk0, not sda, sdb, sdc and mmcblk0?

https://redd.it/129m660
@r_bash
Script Complete for now

I finally have the noscript i was working on all day yesterday to a point where it works. There is a couple of nuances id like to refine number 1 being 1.) Have the Choice menu pop up after completion of each section. I know its probably an easy fix but....as I seen yesterday nothing is as simple as you think it is. Following is the noscript i have that works.

#!/bin/bash

var1=/home/mib2/WorkTest/SavedData
var3=/home/mib2/WorkTest/Item1_Data/
var4=/home/mib2/WorkTest/Item2_Data/

cat /home/mib2/WorkTest/paths.txt #Prints the 3 paths above form .txt file)

PS3='Choose what you want to do: '
choices=("Make_Directory" "Copy_Item2_Data" "Copy_Item1_Data" "Tar_Data" "Quit")
select item in "${choices[@]}"; do
case $item in

"Make_Directory")
cd $var1
echo "What is the new directory to save data going to be called?"
read var2
mkdir -m 777 $var2
echo ""
echo "Directory has been made"
echo ""
echo "The Contents of $var1 is now: " ; ls -al --color=none $var1
var5=/home/mib2/WorkTest/SavedData/$var2
echo "The new Data Name and its Location is: $var5 "
;;


"Copy_Item2_Data")
# Generate list of files in directory
echo "Please enter a directory path which has the Truth Data contained within: "
ls $var4 | grep 20230331

# Ask user to choose a file
echo "Please choose the Data to copy:"
read file_name

# Copy chosen file to another directory
cp -r "$var4/$file_name" "$var5"
echo "The file has been successfully copied to $var5"
ls -al --color=none $var5
;;

"Copy_Item1_Data")
# Generate list of files in directory
echo "The following directories or files are in the Item1 Data directory:"
ls $var3 | grep 20230331

# Ask user to choose a file
echo "Please choose a file or Directory to copy:"
read file_name2

# Copy chosen file to another directory
cp -r "$var3/$file_name2" "$var5"
echo "The file has been successfully copied to $var5"
ls -al --color=none $var5
;;


"Tar_Data")
# Generate list of files in Saved Data directory
echo "The following directories or files are in the Saved Data directory:"
ls -al /home/mib2/WorkTest/SavedData

# Ask user to choose a file
echo "Please choose a Directory to tar:"
read file_name3

#cd $var1
tar -cvf $var5.tar $var5
chmod 777 $var5.tar
break
;;

"Quit")
echo "User requested exit"
exit
;;
*) echo "invalid option $REPLY";;
esac
done

https://redd.it/129n103
@r_bash
How can i send email with bash noscript/from terminal

Im trying to write a noscript that will send email every day about some information about system. I tried sendmail and curl from terminal but i couldnt send email. Anyone can enlighten me? I am using arch linux.

https://redd.it/129o2mp
@r_bash
how bad of an idea is it to pipe (via named pipe) something into an interactive shell?

I have a noscript, `pipe-reciever.sh` that takes output of a named pipe and pipes it into an interactive shell:

#!/usr/bin/env bash
tail -f test_pipe | bash -i

(tail is used here so that bash doesn't exit after 1 input). Since any process can write to this, is it a huge security hole? if the pipe is in my home directory and a malicious process can write to the pipe, it can execute arbitrary code. Is it any different than if the same malicious process could write arbitrary code to a config file e.g. my .bashrc?


Why am I doing this? (backstory/possible XY problem): I want to trigger some of my bash keybindings programmatically. I've found it's possible by running my pipe-reciever noscript and sending the keys using another noscript like:
`printf $'\cp\ct' > test_pipe`
which will send a `C-p C-t` sequence and the interactive shell will execute the appropriate key binding, which I defined in my .bashrc.

I really do need to trigger these bindings programmatically: I'm using bash's keybinding functionality to supplement an app called [Key Mapper](https://github.com/keymapperorg/KeyMapper) which is no longer being actively developed. I'm using Key Mapper to execute shell noscripts in Termux. These shell noscripts contain variations of the `printf` command from above which trigger my bash keybindings.

https://redd.it/129yc7s
@r_bash
Bash noscript with some steps

So i am trying to write a bash program that will capable with these steps:

1. Every night, program list all belows and send mail to related person.
1. Which users are logged in
2. How was the overall performance of ram, cpu etc
2. When user wants to use rm -rf command, program should ask "you sure" and if user type yes it will be deleted
3. Program need to list all the changes done on environment on a file. When new user logged in it will show 10 changes as a list.

I used debug_trap but couldnt make it work for rm part. I am not sure what i need to list as environment changes and how to detech if new user logged in. Thanks in advance.

https://redd.it/12aczvm
@r_bash
Problem with single quotes

I'm trying to display the following string, without modifying the variable content and keep double and single quotes intact:

noscript="I don't look good when I cry"
/bin/bash -c "printf '$noscript'"

Is possible?

https://redd.it/12aeq1u
@r_bash
How can I ignore first letters when searching with fzf?

I looked up changing the search scheme scoring criteria for fzf but that seemed to be too complicated for the task I want and gave up. I'm also confused if it can be done with -n or --nth options. The -n option works but only for numbered index of letters. Here I want it after specific part not a numbered index. I'm also aware of the --tiebreak=end option which helps, but still I want to completely ignore the first part of fields.

I just want to search the last part of a string.

Example: I want to search the last words of path after the final / only:

 echo -e '/ignore/these/words/here/Search This\n/ignore/these/words/here/Also Here\n/ignore/these/words/here/And These Words' | fzf  


How can I do that without changing the phrases of echo themselves? I want fzf to search what I need to be ignored in those examples.

Thank you in advance for any help

https://redd.it/12ax9j7
@r_bash
Help with renaming set of file

I have few files in a folder

the naming convention is

Mon 20230304 p.1 Matter and Teaching.m4a
Mon 20230304 p.2 Matter and Teaching.m4a
Sun 20230310 p.1 Matter and Music.m4a
Sun 20230310 p.1 Matter and Music.m4a
etc

I'd like to swap the position of the first two strings - so it starts with the date and then gives the day of the week -

2023_03_04 Mon p.1 etc

Any one can suggest a quick way to do it?

https://redd.it/12ay937
@r_bash
I just learned about rlwrap, that can let your read commands be readline enabled with history and filename completion. (Tip)

rlwrap seems like a nice program that lets you use bash's readline extension, for history and filename completion, for programs that reads input from stdin, but doesn't give access to readline.

I think you need some Unix like operating system to leverage upon this "wrapper".

If you run a Unix, or Unix like operating system, then there is a high probability
that it is available in your repository.

There are other options like socat, but rlwrap is specialized for just this task
of enabling readline for programs that doesn't utilize them,, like bash's read command.

I haven't tried it yet, as I have just installed it, but I came by it by reading a manual page
for something else, and it is in the apt repository, so I think it should be all good.

You can read about it here at it's github repo.

https://redd.it/12b0woi
@r_bash
build latest version of curl from source and install to correct directory

Hey, fellow bash enthusiasts. I got into building curl from source to take advantage of more recently added features. As one does, I noscripted it so I can do this programmatically. I'd love some critique on any aspects of the noscript. I have a few specific points too:

- Is it reckless of me to purge the host's installed curl and then try to build from source? Do I need to trap failures so I can re-install curl if it was originally present? (I.e., clean up after a failure?)

- For downloading the source, instead of installing/purging curl, should I just fall back to wget (and other things) if curl isn't initially available for downloading the curl source?

- Is it unreliable to use "which curl" to determine where on the system curl likes to live?

- Do I need more sophisticated error checking around the make/make install steps?

Thanks for taking a look and sharing your feedback. Much appreciated!

_

#!/usr/bin/env bash

# debugging switches
# set -o errexit # abort on nonzero exit status; same as set -e
# set -o nounset # abort on unbound variable; same as set -u
# set -o pipefail # don't hide errors within pipes
# set -o xtrace # show commands being executed; same as set -x
# set -o verbose # verbose mode; same as set -v

source ./functions.sh

die-if-not-root

apt-get -y update && apt-get -y upgrade

TEMP_DIR=$(mktemp --directory)
cd-or-die "${TEMP_DIR}"

if program-not-available curl; then
apt-get -y install curl
fi

die-if-program-not-available curl "An existing \`curl\` isn't available, so the noscript can't determine where to install a new \`curl\`."

# find where curl lives, so we can install new curl using the same directory path prefix
CUR_CURL_PATH=$(which curl)
PREFIX_FOR_MAKE=$(echo "${CUR_CURL_PATH}" | sed "s,/[^/]*$,," | sed "s,/[^/]*$,,")

# get latest stable version of curl
LATEST_VER=$(curl --silent https://curl.se/changes.html | grep --max-count 1 --only-matching --perl-regexp "(?<=<h2> Fixed in ).*?(?= -.*)")
ARCHIVE_BASENAME="curl-${LATEST_VER}"
curl --location --show-error --silent --url "https://curl.se/download/${ARCHIVE_BASENAME}.tar.gz" --output "${TEMP_DIR}/${ARCHIVE_BASENAME}.tar.gz"

# remove existing curl, so we can install a new one
apt-get -y purge curl

if ! tar -xzvf "${ARCHIVE_BASENAME}.tar.gz"; then
die "Couldn't extract source code via \`tar\`."
fi

# install dependencies for build
apt-get -y install libbrotli1 libbrotli-dev
apt-get -y install libssh2-1 libssh2-1-dev
apt-get -y install libzstd1 libzstd-dev

cd-or-die "${ARCHIVE_BASENAME}"

if ! ./configure --enable-websockets --prefix="${PREFIX_FOR_MAKE}" --with-brotli --with-libssh2 --with-nghttp2 --with-ngtcp2 --with-openssl --with-zstd; then
die "\`configure\` failed."
fi

if ! make; then
die "\`make\` failed."
fi

if ! make install; then
die "\`make install\` failed."
fi

die-if-program-not-available curl "Building \`curl\` seemed to work, but \`curl\` can't be located."



I utilize some helper functions of mine in another noscript. Here they are, if someone wants to see them:


#!/usr/bin/env bash

# usage: die "$MESSAGE"
die() {
printf >&2 "\n*\n* Error: %s\n* This error is unrecoverable. Check above for additional error messages.\n*\n\n" "${1:-Unspecified error.}"
exit 1
}

# usage: am-root
# returns 0 if root, 1 if not root
am-root() {
if ((${EUID:-$(id -u)} != 0)); then
return 1
else
return 0
fi
}

# usage: die-if-not-root
die-if-not-root() {
if ! am-root; then
die "Please run this noscript as root (e.g., using ‘sudo’)."
exit 1
fi
}

# usage: die-if-root
die-if-root() {
if am-root; then
die "Please run
this noscript as a non-root user (e.g., not as root, not using ‘sudo’)."
exit 1
fi
}

# usage: die-if-program-not-available $PROGRAM_NAME "$MESSAGE"
die-if-program-not-available() {
program-not-available "${1}" && die "${2}"
}

# usage: program-not-available $PROGRAM_NAME
# returns 0 if program isn't available, 1 if program is available
program-not-available() {
program-available "${1}" && return 1
return 0
}

# usage: program-available $PROGRAM_NAME
# returns 0 if program is available, 1 if program isn't available
program-available() {
command -v "${1}" >/dev/null 2>&1 && return 0
return 1
}

# usage: die-if-file-not-present $FILENAME_WITH_PATH "$MESSAGE"
die-if-file-not-present() {
[ ! -f "${1}" ] && die "${2}"
}

# usage: cd-or-die $DIRECTORY "$MESSAGE"
cd-or-die() {
cd "${1}" || die "Couldn't cd to ${1}."
}

https://redd.it/12b944i
@r_bash
Problems with sudo and single quote.

I executed the following command in interactive bash, but output from echo contains string '-e'.

```shell

sudo -u root sh -c 'for name in raw mangle nat filter; do echo -e "#######$name#######\\n"; iptables -t $name -nvL; done'

```

https://redd.it/12bfhw6
@r_bash