FAQ Database Discussion Community


Increment of multiple file prefixes?

bash,sh
I am looking for a way in Bash to rename my file prefixes. These files are all in one folder. No other files will be in it. 00 - Artist - Title.mp3 01 - Artist - Title.mp3 ... and so on to 01 - Artist - Title.mp3 02 - Artist...

Pass command line arguments from bash script to program verbatim, with escaping

bash,unix,sh
So, I have a bash script that needs to run X if --xyz flag is set, and Y otherwise. It also needs to pass all command line arguments through to the programs it runs. My problem with this is that I can't get it to pass the arguments exactly as...

source: not found error while running shell script on ubuntu 14.04

django,bash,cron,sh,ubuntu-14.04
OS- Ubuntu 14.04 This is my shell script which i want to schedule using cron job. parser.sh #!/bin/bash source .profile workon venv cd /home/ashish/deployments/myproject export DJANGO_SETTINGS_MODULE=myproject.settings_production python /home/ashish/deployments/myproject/myproject/manage.py parse_data Cron job- */15 * * * * . /home/ashish/parser.sh Whenever this cron job runs i receive a mail with errors: /bin/sh:...

how to extract grep and cut into a bash array

linux,bash,shell,sh
I tried: here is content of file.txt some other text #1.something1=kjfk #2.something2=dfkjdk #3.something3=3232 some other text bash script: ids=( `grep "something" file.txt | cut -d'.' -f1` ) for id in "${ids[@]}"; do echo $id done result: (nothing newline...) (nothing newline...) (nothing newline...) but all it prints is nothing like newline...

BASH : Difference between '-' and '--' options

linux,bash,shell,sh,ls
I was working my way through a primer on Shell (Bash) Scripting and had the following doubt : I came across the ls command The man page of ls lists a few use cases as : ls -a ls --block-size='M' My Question : What is the difference in - and...

How to execute command when df -h return 98% full

linux,shell,sh
How to execute command when df -h return 98% full I have a disk which is by the /dev/sdb1 917G 816G 55G 94% /disk1 If its return 98% full, I would like to do the following find . -size +80M -delete How do I do it, I will run the...

Confirming Shell Script Input

bash,shell,sh
I'm writing a script to preform a repetitive task that only changes basic values and locations such as user name. I've written up code that prompts for a username and verifies that it is not already in use. I'm now trying to prompt the user if the input the script...

Is it possible to check the output of previous step in the same script

bash,sh
The script runs two scripts depending on the output of the first script, i want to choose to run the script or not. For e.g Mainscript.sh ./script1.sh.... is there a way to check output of script1.sh in mainscript.sh? Because if output that there is connection between two system then i...

How to extract value of root variable from kernel commandline

linux,bash,sh,busybox
I want to extract the value set to the root variable in following kernel command line, I don't want to use awk column number. console=ttyO0,115200n8 noinitrd mem=256M root=/dev/mmcblk0p2 rw rootfstype=ext4 rootwait=1 ip=none I am able extract it using following command but it depends on the position of root variable but...

how to deletes line from a text file that are taken from another file [duplicate]

shell,awk,sed,grep,sh
This question already has an answer here: Remove duplicates from text file based on second text file 4 answers I have a data.txt file with a lot of lines in it and a lines.txt that contains some lines. I want to delete all lines from data.txt that match any...

Bourne shell: split string according to multiple criteria (iptables multiport limitation)

string,shell,split,sh
I am writing a routine in Bourne shell to command iptables, which does an intensive use of the "multiport" parameter. iptables allows maximum 15 references to the multiport parameter. These references can be individual (counting 1) or ranges (counting 2). I would need to break a long string of ports...

Getting duplicate output

bash,scripting,sh
I'm trying to write a bash script that looks for a file in one directory and replaces it with one of the same name from a source directory. When I run the find command, it seems to be setting my $path twice for f in build-res/$1/*.png; do file="$(basename "$f")" echo...

Python Sh Library for MySQL dump import using output redirection (<) pipes

python,mysql,pipe,sh
I am using Python Sh (https://amoffat.github.io/sh/) and I was wondering if its possible to use <> pipes as well? Mainly I am talking about mysql < dump.sql. I was thinking about using mysql -D db -e "source mydump.sql' but source is not recommended for that. Is there any other options?...

PHP5, Shell_exec waiting for spawned linux shell tasks to finish

php,linux,multithreading,shell,sh
I am trying to start a linux shell script from PHP5 that will run for 24hours, but I want the webpage to return within seconds. I though this could be solved by making a script spawning of the task, but it does not seem to work. I have been searching...

“Filename argument required” warning when running shell command from bash_profile

bash,unix,terminal,sh
I'm customizing my .bash_profile in my Mac's Terminal. I want to make a function that either runs a ruby file or opens it in a text editor, depending on my arguments. I'm very new to doing anything more with Terminal than just installing stuff. Here's what I've got so far:...

cut text file and get the first field bash

grep,sh,cut
i had a problem with using grep, or cut command to get out the files size i have that file : 4096 Feb 15 21:52 f1 0 Feb 15 18:24 f4 6928808 Feb 10 16:59 install_flash_player_11_linux.i386.tar.gz 87 Feb 14 18:43 sc1.sh 281 Feb 14 19:11 sc2.sh 168 Feb 14 21:40...

Redirect stdout using exec in subscript

linux,bash,redirect,command-line,sh
I have one main script which is started as an service. I can't modify this main script, because it is often updated. This main script starts a program, which echo any log to stdout. So i can't see any log of this program. But this main script calls at the...

Environmental variable is empty into shell script but not in shell

android,bash,shell,sh,libvlc
A shell script checks some of my environmental variables, but this code: if [ -z "$ANDROID_NDK" -o -z "$ANDROID_SDK" ]; then echo "You must define ANDROID_NDK, ANDROID_SDK before starting." echo "They must point to your NDK and SDK directories.\n" exit 1 fi prints out You must define ANDROID_NDK, ANDROID_SDK before...

Unwanted text file is creating while calling a URL through Cron

ruby-on-rails,ruby,cron,sh
In our application we are configured number of Cron jobs for running some routine tasks.We are working on Ruby on Rails. I will provide the flow we are using. crontab */2 * * * * user sh file_path/test.sh test.sh wget https://domain.com/url/key routes.rb post "/url/:key" => "cron_job_controller#action" cron_job_controller.rb def action if...

db2 - export into File

unix,db2,sh
I'm trying to export the result of a query in db2 to file, but the result like: +000000869836.|+00000000000001401. +000000978137.|+00000000000000511. What can I do to obtain the following result: 869836.|1401. 978137.|511. My current query: EXPORT TO /tmp/tmp.tmp OF del modified by NOCHARDEL coldel| select iv.bpd_instance_id, max(case when alias = 'abc' then...

Running stored command with environment variables

sh
This works in sh: $ export command="true" $ "$command" If I need to pass some variable to the command, however, I can't get it to work: $ export command="env FOO=\"bar\" true" $ "$command" sh: 2: env FOO="bar" true: not found What is missing?...

How to limit the CPU usage of a dash loop that listens for a filesystem change?

loops,sh,cpu-usage,dash
I wrote a loop in dash which waits for a file to appear in a certain location on the filesystem. But when it runs it takes up 50% of the CPU. I first lowered the CPU usage using a sleep command but the minimal sleep time in dash (1 second)...

shell command to skip file in sequence

shell,sh
I run a C++ code for several data files in sequence using: for i in $(seq 0 100); do ./f.out c2.$(($i*40+495)).bin `c2.avg.$(($i*40+495)).txt; done` Now if some input files are missing, say c2.575.bin is missing then the command is not executed for the rest of the files. How could I modify...

Validating file records shell script

linux,bash,shell,unix,sh
I have a file with content as follows and want to validate the content as 1.I have entries of rec$NUM and this field should be repeated 7 times only. for example I have rec1.any_attribute this rec1 should come only 7 times in whole file. 2.I need validating script for this....

Printing a “Hello World” in bourne shell without directly using white space char

linux,sh
I'm currently trying to solve a tricky/silly challenge and i've come to a dead end. The challenge is basically to form a one-liner /bin/sh compatible command line which essentially outputs "Hello World" without directly typing White space or Tab characters in the command itself. for example something like - echo...

Storing data in shell

shell,sh
I have a need to store a list of e-mails in a shell script. This script will get called and passed a customer number. depending on the customer number I want to populate a variable based on the passed in customer number. I am not sure how to accomplish this...

How to write and match regular expressions in /bin/sh script?

regex,shell,unix,sh
I am writing a shell script for a limited unix-based microkernel which doesn't have bash! the /bin/sh can't run the following lines for some reasons. if [[ `uname` =~ (QNX|qnx) ]]; then read -p "what is the dev prefix to use? " dev_prefix if [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then...

Unicode characters in /bin/sh VS /bin/bash

bash,unicode,sh,chars
Please try: bash -c "printf '\u2744'" bash -c "echo -e '\u2744'" And so: sh -c "printf '\u2744'" sh -c "echo -e '\u2744'" Why in /bin/bash I can get that unicode character but not in bin/bash? How to print a unicode characer (for example ❄) in /bin/sh?...

Cross fading several audio files using sox

bash,audio,sh,sox,cross-fade
I'm trying to cross-fade several audio files together with a 3 second cross-fade and join them together in to one file with sox. I can join several files together by the command below but not sure how to cross fade between each one: sox $(ls /tmp/a*.wav | sort -n) /tmp/out/out.wav...

No rule to make traget Install (Kubuntu Konsole)

make,sh,kubuntu
I am trying to install the following database: aleda-latest.zip In the Konsole I type the following command: $ make install output: bzcat ne_vars.fr.dat.bz2 > ne_vars.fr.dat bzcat ne_refs.fr.dat.bz2 > ne_refs.fr.dat make: *** No rule to make target« /usr/local/share/alexina/fr », needed by « lefff.dat ». Stop. What seems to be the problem?...

BASH find file names but skip a list of file names

bash,printf,sh,filenames
I'm trying to set up a process in BASH from the "find" output. However I also have a list of file names that should not be process but they are in the same directory. I can't differentiate the files by file type. An example is the following: m001.png m002.jpg m003.tif...

sh boolean short circuit variable assignment

bash,sh,variable-assignment,short-circuiting
I'm trying to write a script that takes flags as parameters, so I want to be able to handle them being passed in any order. This is what I have so far: #!/bin/sh numargs=$# echo $numargs check_param () { if [ "$1" = "$2" ]; then return 1 else return...

Linux Rename Multiple Files At a Shell Prompt

linux,sh
I want to change: Input: changing_colorlow_actual_take000000.png Output: changing_colorlow_expected.png This is just an example. There are multiple files i need to rename. Basically I need to replace complete string from "_actual_xxxxxxxxx.png" to "_expected.png" What is the Code for it to run on Linux Machine??...

how to align the decimal values in a ksh script report

shell,awk,sh
am trying to align the value inside awk.. but still am facing some alignment issue.. could you please help. am getting below format., Code 0011 0.00 Code 0012 0.00 Code 17 1,234.23 Code 37 123,456.12 Code 41 2,345.12 Total Amount 8.41 0011 Record Count 0 0012 Record Count 0 17...

Pipe that does nothing

bash,sh,ksh,nop
I'm on a AIX box and need a program that when used after a pipe does nothing. I'll be more exact. I need something like this: if [ $NOSORT ] ; then SORTEXEC="/usr/bin/doesnothing" else SORTEXEC="/usr/bin/sort -u" fi # BIG WHILE HERE do done | SORTEXEC I tried to use tee...

Shell script to build CLI args for a PERL script

sh,double-quotes,single-quotes
I have a Jenkins job, triggered as a parameterized build. It accepts an optional String parameter (HOSTNAMES) that can be a comma separated list of hostnames. I need to pass this comma separated list of hostnames as a command line argument to a PERL script (within Execute shell build step)....

Why doesn't ${#$2} work?

bash,sh
I have this line in a small bash function: if [ ${#$2} -lt 25 ]; then But it gives me Bad substitution on the ${#$2}. What am I doing wrong there? I'm trying to get the length in characters of the second command line argument. How can I do this?...

How can I detect if some file in a subdir changed?

linux,console,sh
Basically I have a big directory (>10GB)(each subdir only has a few other subdirs) and want to do sth to any files that changes. I can't just go through all the files and check, because it takes to long and uses about 90% of my CPU :(. This is how...

Passing a pre-defined variable from shell script to shell script in Linux

linux,bash,shell,variables,sh
This is my first time using a shell script. I have one "Mother" script mainscript.sh, in which I define the variable patientid. patientid=`basename $folder` Later on in the same script, I wish to execute a separate script example.sh while passing the variable patientid into it. That script already has the...

Format a number with thousands separators in shell/awk

awk,sh
awk -F, ' { printf(" Code %s %s\n",$1,$2) r[NR] = $1 c[NR] = $3 } END { for(i = 1; i <= NR; i++) printf(" %s Record Count %s\n", r[i],c[i]) }' totalsum.txt this is my input file 17,123456,1 16,1234,2 0211,34567,2 21,2345,2 am getting output like below., Code 17 123456 Code...

Linux - sh script - download multiple files from FTP

linux,ftp,sh
I need script that can download files from ftp via my sh code I have use expect with ftp, but if I do for loop inside code, I got wrong # args: should be "for start test next command" while executing "for v in "a b c"" My code /usr/bin/expect...

How to set the timer in shell

shell,sh
Can we set the timer in shell script? means if I set the timer for 20 secs my shell scripts should be execute like this : 20..19..18..17.. after completing the I should get the result. Is it possible ? Please assist me....

How to run shellscript parallely like java thread

shell,unix,sh
Hi I have a script mainscript.sh In main script I have multiple chile script. child1.sh child2.sh child3.sh rm -rf /home/bdata/batch/* I am running my mainscript.sh which will run all child jobs in parallel. mainscript.sh child1.sh & child2.sh & child3.sh & rm -rf /home/bdata/batch/* 4th statement runs before completing all the...

How can `time` control other processes trough a pipe?

time,pipe,sh
In the general case we have a command like P | Q | R which has the following semantics for the shell: Create a processes P, Q, R Bind the output of P to the input of Q Bind the output of Q to the input of R Bind the...

Why can I save a .sh file as .txt and it still works when I run it

sh
I have this in my myshellscript.txt: #!/bin/sh if [ -f $1 ] then cat $1 else echo "Sorry, not found" fi Why is that even though it is a .txt file I can still run it using sh myshellscript.txt someotherfile.txt...

error to delete files older than 1 day form csv list

sh,ksh,aix
I want to delete files in a directory, from the supplies csv file if its older than 1 day. I tried to print them for test purpose: in.txt 1,one 2,two code: INPUT="in.txt" while IFS=',' read -r id name do find tmp/$name -mtime +1 -type f done < "$INPUT" Ths code...

File name contains pixel dimensions that need to be converted to inches

bash,sh,exiftool
I am about to receive 1000+ files that will need to be renamed so the names contain their print dimensions. I've figured out how to extract the pixel dimensions and rename the files to include that with exiftool but I'm not sure what the best approach is for automating the...

Why does using virtualenv commands in .sh file give “command not found”? [duplicate]

osx,bash,sh
This question already has an answer here: virtualenvwrapper functions unavailable in shell scripts 7 answers I am trying to automate the removal and recreation of a virtualenv on a Mac (Mavericks). I have a file clean_venv.sh: #!/bin/bash echo "Start" deactivate rmvirtualenv test mkvirtualenv test This gives: Start ./clean_venv.sh: line...

Syntax error: “fi” unexpected (expecting “then”) in bash script

bash,command-line,scripting,sh
I try to do the script: #!/bin/bash IP='192.168.1.1' fping -c1 -t300 $IP 2>/dev/null 1>/dev/null if [ "$?" = 0 ] then echo "Host found" else echo "Host not found" fi and i turn it: [email protected] ~ $ sh /home/pi/sh/test.sh /home/pi/sh/test.sh: 9: /home/pi/sh/test.sh: Syntax error: "fi" unexpected (expecting "then") where is...

How to split and iterate substrings by delimiter in BOURNE SHELL?

string,shell,loops,split,sh
Recently I've been trying to customize my shell profile located at ~/.profile in Ubuntu. One thing I want to do is: # PATH-like variable containing paths separated by ':' MY_ROOTS=/f/o/o:/b/a/r:/e/t/c for some magic iterating my_root in $MY_ROOTS do; my_bin="$my_root/bin" # add it to PATH! [ -d "$my_bin" ] && {...

Sort and counting a column without uniq in bash

linux,bash,sorting,count,sh
I want to add a count of only the first column using bash, without doing uniq, like this: input: 58311s2727 NC_000082.6 100.00 50 58311s2727 NC_000083.6 100.00 60 58311s2727 NC_000084.6 100.00 70 58310s2691 NC_000080.6 100.00 30 58310s2691 NC_000081.6 100.00 20 58308s2441 NC_000074.6 100.00 50 output: 3 58311s2727 NC_000082.6 100.00 50 3...

remove everything exept for .git directory and .gitignore on linux

linux,bash,find,sh,ubuntu-14.04
Hi I'm trying to delete every thing in a folder using the linux commandline except for the .git directory and the .gitignore file #!/bin/bash cd /git/ # remove old files find . ! -name '.gitignore' ! -path '.git' ! -path '.git/*' -exec rm -rf {} \; It kind of works,...

ANSI escapes don't work in `printf`

bash,printf,sh,ansi-colors
When trying to use ANSI color escapes from a shell script, I was completely stuck, as the escape sequences (\e) were printed verbatim to the output. #!/bin/sh GREEN="\e[32m" RED="\e[31m" CLEAR="\e[0m" printf "${GREEN}test passed${CLEAR}\n" printf "${RED}test failed${CLEAR}\n" Produces \e[32mtest passed\e[0m \e[31mtest failed\e[0m ...

Bash Script to generate csv file from text

bash,shell,sh,export-to-csv
I have a text file with records: Data1 Data2 ... Data50 I have to create a .csv file from the above text file in the following format: Type | Count | Name Def | u1 | Data1 Def | u2 | Data2 .... | ..... | .... Def | u50...

Split lines on separator but just two slices

bash,shell,awk,sh
I want the delimiter to work only once so the line can be split into only two parts. I tried something with awk with = as delimiter, but it splits the line into three parts if there is second =. Given the file file.txt: first="text" line="book" red=cat nice="lineelrk=" I am...

os.Exec and /bin/sh: executing multiple commands

bash,shell,go,sh
I've run into an issue with the os/exec library. I want to run a shell and pass it multiple commands to run, but it's failing when I do. Here's my test code: package main import ( "fmt" "os/exec" ) func main() { fmt.Printf("-- Test 1 --\n`") command1 := fmt.Sprintf("\"%s\"", "pwd")...

Showing progress as shell script runs

shell,sh,snmp,net-snmp
I would like to display something showing that the script is still gathering information from a device. Whether it be hash marks or periods. As you can see below when it starts its walk of a device it echos its start time. It is here I would like to show...

How to append entry the end of a multi-line entry using any of stream editors like sed or awk

linux,bash,awk,sed,sh
I am trying to use a script to append the host name at the end of a multi-line entry of a specific Host_Alias field in sudoers file. The current sudoers file has an entry similar to : Host_Alias srv_linuxestate= \ host10,host12,host13,host1,host50,\ host16,host1,host2,host11,host15,host21,\ host3,host14 My required output would be something like...

Error in check_call() subprocess, executing 'mv' unix command: “Syntax error: '(' unexpected”

python,bash,shell,sh,travis-ci
I'm making a python script for Travis CI. .travis.yml ... script: - support/travis-build.py ... The python file travis-build.py is something like this: #!/usr/bin/env python from subprocess import check_call ... check_call(r"mv !(my_project|cmake-3.0.2-Darwin64-universal) ./my_project/final_folder", shell=True) ... When Travis building achieves that line, I'm getting an error: /bin/sh: 1: Syntax error: "(" unexpected...

Printing a newline

bash,sh
GAAAAAAAAAAAAAAH I don't know why I'm struggling so much with this. All I want to do is make: file="$a"[command-here]"$b" to make $file= a [newline] b And yet no matter WHAT echo or printf I try to use, I cannot get it to work!! I just want a newline between a...

Running an executable by calling it in a .sh file

bash,sh
I am very new to bash and using .sh files. I am trying to run the program aescrypt by calling it in a .sh file as follows (aescrypt is in the same directory as the .sh file) : ./aescrypt -e -p password file.txt It throws the following error: ./aescrypt no...

Length of array of files not correct in shell

shell,sh
I have the following script: #!/bin/sh FILES=../folder/files/* echo "Total files in array : ${#FILES[@]}" for f in $FILES do echo "Processing file $f" done In ../folder/files/ I have 3 files and the for loops through them properly. However, the number of files in array is incorrect. It returns 18 instead...

Get variable outside WHILE in SHELL BASH script

mysql,bash,shell,sh,do-while
How echo variable x and y outside "while" in SHELL script: #!/bin/bash x=1 y=1 mysql -e "show tables like 'do97_%';" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel | while read tables; do mysql -e "SELECT id, tolbox, del_time FROM $tables WHERE deleted=0 ORDER BY create_time DESC LIMIT 0" --host=localhost --skip-column-names -u...

Run a C program from within a C program

c,runtime,system,sh
The question pretty much explains itself I have three different C programs and to try and compare their efficiency I tried to test their runtime by making them run several times varying their parameter (which is proportional to time taken) and write how long it takes each program to run...

Why does Scala use a reversed shebang (!#) instead of just setting interpreter to scala

bash,scala,sh
The scala documentation shows that the way to create a scala script is like this: #!/bin/sh exec scala "$0" "$@" !# /* Script here */ I know that this executes scala with the name of the script file and the arguments passed to it, and that the scala command apparently...

evaluation of logical expression chain in /bin/sh

sh
I have trouble understanding how this posix shell code works. my_dir=/tmp/foo_dir [ -d $my_dir ] || mkdir -p $my_dir || echo "Error creating '$my_dir'!" Consider the case where the directory does not exist. -d returns zero if directory doesn't exist, so then the "mkdir" is evaluated. mkdir returns zero upon...

SIGHUP signal handler reset to default when using system() on embedded linux with busybox

c,linux,sh,busybox
I am working on an embedded linux with busybox. As part of my application I have a rc.init script E80-startmyprog. That script is calling my program prog. trap "" HUP startmyprog >${LOGFILE} 2>&1 </dev/null & startmyprog() { prog } In my program I can see that the signal handlers are...

Disregard word order when comparing two variables

shell,unix,sh
I want to compare two variables using shell. $a="abc pqr mno xyz" $b="mno pqr xyz abc" Here two variable values are same (just words order is not same inside the variable). If i compare $a and $b it will say that $a and $b are not same, but I want...

Bash quirk when passing string from command line

bash,shell,scripting,sh
This is an example I created to demonstrate the quirky behavior. I expected bash to pass the quoted command line argument as is. [email protected]:~/tmp$ cat script.sh #! /bin/bash set -o xtrace $1 sleep 3 [email protected]:~/tmp$ ./script.sh "echo" + echo sleep 3 sleep 3 [email protected]:~/tmp$ ./script.sh "echo -n" + echo -n...

Error on retrieving array length in bash

bash,shell,sh
I've been trying to run a simple script that retrieves the penultimate subdirectory of a variable size directory. But it fails miserably to retrieve its length. The script goes: ARRAY=$(ls files-0/var/log/) echo ${#ARRAY[@]} for i in ${#ARRAY[@]}; do echo $i done The output I get is: 1 1 If i...

Checking for lack of flags in bash

bash,scripting,sh,getopts
If I were to do something like this to process arguments in bash, how would I check if there were no arguments? It doesn't seem to go to the *) case, but I'd still like to put a usage statement in there somewhere. while getopts 'ias' flag; do case "${flag}"...

Testing truth/falseness in bash script

osx,bash,shell,sh
For some reason, I can't figure out how to test truth in bash: #!/bin/bash FORCE_DELETE="" BE_VERBOSE="" OPTIND=1 while getopts ":fv" FLAG "$@" ; do if [[ "$FLAG" == "f" ]] ; then FORCE_DELETE="true" fi if [[ "$VALUE" == "v" ]] ; then BE_VERBOSE="true" fi if [[ "$FLAG" == "?" ]]...

Order lines by number of occurrences

list,shell,sh
Given a list with one element per line (with occasionally some blank lines), e.g.: 22008 6881 6881 22008 6881 22008 22008 6881 56515 8080 8080 56515 22008 45682 45682 22008 I would like to get as output a list with unique items sorted by number of occurrences: 22008 - 6...

sh script vulnerability in Linux

linux,security,sh
I was given an assignment for my Computer Security class. We we were given a piece of code to analyze and determine the vulnerabilities that it might have. #!/bin/sh # shell script to create a copy of the shadow file to the /tmp directory echo > /tmp/shadowcopy # allow only...

Bash script - Auto fill answer

linux,bash,shell,sh,auto
I have a bash script that has several questions, is it possible to automatically fill the answers ? ./script.sh install answers in order y 2 1 n n How can I do that in bash ? edit: is it possible to only pass the first answer ? echo "y" |...

How to negate multiple conditions in the Bourne shell

shell,sh
I have a simple Bourne shell script like this: if ! pwd && ls && mkdir /opt/test/; then echo "failure" else echo "success" fi I want it to report a failure if any of the commands does not exit successfully e.g. if the mkdir command fails due to insufficient permissions....

Bash if number greater then failing

bash,sh
Can anyone explain to me why this is failing? 0111 is greater then 99 but i'm not getting an Invalid database message. db=0111 echo $db £ Verify db is within the correct range if [[ $db -lt 0 ]] || [[ $db -gt 99 ]]; then echo "Invalid database" fi...

Strange issue relating to shell script files

linux,bash,shell,unix,sh
I have this shell script inside a file called restart_server.sh: echo "KILLING SERVER SESSION" kill $(cat serverlastpid.txt) sleep 20 echo "STARTING SERVER..." java -jar eu.greensmartcampus-0.0.1-SNAPSHOT-jar-with-dependencies.jar </dev/null>/dev/null 2>&1 & echo $! > serverlastpid.txt echo "SERVER STARTED! PID:" $(cat serverlastpid.txt) If I execute each line individually I get this: [email protected]:/opt/AppServer# echo "KILLING...

Linux shell file. mkdir and pushd commands not doing what I'd like

linux,shell,sh,mkdir
I'm trying to create a directory if it does not exist, and the further down the line, create a log file in that directory. It would be in the current users home directory In pseudocode: If directory "/home/LOGS" does not exist make directory "/home/LOGS" Then whenever a log file is...

Shell command for character replacement

linux,shell,sh
i have this string: "abcdef" and i would like to replace each character with another string. I made it with sed but is making a conflict and if on the replaced string there is another character for example the a it replaces again the a with the string. for example:...

Bash Script_ Inserting variable read from read command into command

linux,bash,curl,sh
I am working on a project using the BLS API. Reference: http://www.bls.gov/developers/api_unix.htm My current script follows: declare id="" echo -n "Enter id: " read id echo -n "enter startyear: " read startyear echo -n "enter endyear: " read endyear curl -i -X POST -H 'Content-Type: application/json' -d '{"seriesid": ["$id"], "startyear":'$startyear'...

Issues with Screen - Running Minecraft in a while loop through a screen session

bash,while-loop,sh,minecraft
So Earlier today, I changed my startup scripts for my minecraft server. Problem is, after about 3 hours, the screen for it that was open vanished and refuses to appear when using -ls. The server is still running and from what I can see below, the screen process should still...

POSIX Shell backslash confusion

shell,sh,backslash
I am trying to create a shell script with a simple functionality, but it seems I can not wrap my head about how to handle backslashes correctly. One of my functions look like this: #!/bin/sh func() { cmd="$*" printf "%s\n" "$cmd" echo -e $cmd } func '%{NAME}\\n' This is the...

BASH convert uppercase to lower case and vice versa at same time

bash,shell,sh
How do i create a program that converts uppercase letters to lower case and vice versa at same time from a given file? I know how to convert each independently #!/bin/sh #Program convert upper to lower cat $1 | tr '[:upper:]' '[:lower:]' #!/bin/sh #Program convert lower to upper cat $1...

Can you import variables into .bashrc?

bash,sh,.bash-profile
I'm looking at having a separate file (e.g. bash_aliases) to hold variables that represent colour characters e.g: Black="\[\033[0;30m\]" # Black Putting this in my rc/profile files would make it look horrendous; is there some way I can simply read in these variables from another file?...

Getting value from function, use that value to get colored output in shell

shell,sh,zsh,zshrc,oh-my-zsh
(Using zsh) I am just trying to get random color output whenever I open a new tab in my terminal. To achieve this I wrote the following shell script, but it is not working as expected: #Standard Colors red='\033[0;31m' NC='\033[0m' # No Color black='\033[0;30m' blue='\033[0;34m' green='\033[0;32m' cyan='\033[0;36m' purple='\033[0;35m' yellow='\033[1;33m' lgreen='\033[1;32m'...

for x in {1..10} in shell script runs only once

linux,ubuntu,awk,sh
The script below stops after one iteration. How do i make it run 10 times? #!/bin/sh for a in {1..10} do echo 'a' x=`sudo hdparm -t /dev/sda` echo $x | awk 'match($0,"= "){print substr($0,RSTART+1)}' >> input.txt done EDIT: the input.txt will have 401.98 MB/sec ..., A list of read speeds....

Get value of variable with the aggregated values of other variables [duplicate]

bash,sh
This question already has an answer here: Bash, Concatenating 2 strings to reference a 3rd variable 2 answers Given: export A='TEST_' export B='VAR' How would I get the value of $TEST_VAR in this case? Some more conditions: should work both on sh and bash of the latest versions. should...

Arguments with spaces are seen as separate arguments and not as one argument [duplicate]

linux,bash,shell,sh
This question already has an answer here: Handle whitespaces in arguments to a bash script 3 answers I have the following functions func() { shift 2; func2 $@; } func2() { echo $1; echo $2; } func 1 2 "3 3" "4 4" I exepect that func2 will dispaly...

How can I run a docker container and commit the changes once a script completes?

bash,docker,sh,commit
I want to set up a cron job to run a set of commands inside a docker container and then commit the changes to the docker image. I'm able to run the container as a daemon and get the container ID using this command: CONTAINER_ID=$(sudo docker run -d my-image /bin/sh...

How do I indirectly assign a variable in bash to take multi-line data from both Standard In, a File, and the output of execution

linux,bash,shell,scripting,sh
I have found many snippets here and in other places that answer parts of this question. I have even managed to do this in many steps in an inefficient manner. If it is possible, I would really like to find single lines of execution that will perform this task, rather...

Convert shell script command to command line

python,shell,sh
I am executing python script with multiple command line parameter, but using shell script. command i execute for shell script execution is: ./scripts/run_qa.sh data/questions/questions.txt data/lexicons/paralex data/weights/paralex.txt data/database > output.txt run_qa.sh files looks like below (please explain how it works): #!/bin/bash set -u set -e if [ $# != 4 ];...

Portable solution to loop through a directory recursively in bash 3.2

shell,unix,sh,portability
I want to loop recursively through every file and directory below an specified path and echo that file/directory's owner and name. I found this question to be a good reference, but I would like to know if there is a bash 3.2 portable and simpler solution to the problem. A...

How to repeat a character in Bourne Shell?

unix,sh
I want to repeat # 10 times, something like: "##########" How can i do it in Bourne shell (/bin/sh) ? I have tried using print but I guess it only works for bash shell. Please don't give bash syntax....

Start epiphany browser from bash and continue script

linux,bash,shell,sh
I want to start my epiphany browser in a shell script and let the script do sth other while browser starts. The Problem i got, the browser is running in the bash window and shows me messages what it blocked etc. The rest of the script is not executed. I...

Writing a bash script from another script in literal mode

linux,bash,shell,scripting,sh
In a bash script I'm creating another bash script to launch a program: $optionsfile="options.conf" tee "launch-script.sh" > /dev/null <<EOF #!/bin/bash bash $binFile `cat $optionsfile` & EOF I want the output script launch-script.sh to be like this: #!/bin/bash bash $binFile `cat options.conf` & So I would like to have the script...