New answers tagged

1

I really can't stand scripts that ask me questions rather than allow me to use command line options (easier to edit and re-use previous command lines, easier to use in a script), so I'd use getopts like this: #!/bin/bash regions=(us-east-1 us-west-2 us-west-1 eu-central-1 ap-southeast-1 ap-northeast-1 ap-southeast-2 ap-northeast-2 ap-south-1 ...


0

Here is a single command which will recursively list symlinks whose target is a directory (starting in the current directory): find . -type l -xtype d Reference: http://www.commandlinefu.com/commands/view/6105/find-all-symlinks-that-link-to-directories


5

Why not make the life of the user a bit easier by not requiring them to type the name of the region at all? #!/bin/bash echo "Select region" PS3="region (1-10): " select region in "us-east-1" "us-west-2" "us-west-1" "eu-central-1" \ "ap-southeast-1" "ap-northeast-1" "ap-southeast-2" \ "ap-northeast-2" "ap-south-1" "sa-east-1" do if [[ -z $...


5

Why don't you use case? case $text in us-east-1|us-west-2|us-west-1|eu-central-1|ap-southeast-1|etc) echo "Working" ;; *) echo "Invalid option: $text" ;; esac


1

You could do something like this: valid=(foo bar doo) echo enter something, valid values: "${valid[@]}" read text ok=0 for x in "${valid[@]}" ; do if [ "$text" = "$x" ] ; then ok=1 ; fi ; done echo is it ok: $ok The valid values are saved in a bash array, which can be used both for display and to test the input string. Apart from the fact that -o ...


4

The problem is with this: [ "$text" != 'us-east-1' -o us-west-2 -o ... ] The -o means or and you need a full condition, so it would be [ "$text" != 'us-east-1' -o "$text" != 'us-west-2' -o ... ] See how we're having to test $text each time? Your logic is also wrong; you want -a (and); if it's not "us-east-1" and it's not "us-west-2" and it's not... ...


1

Make sure you quote the URL if running this from a shell like bash or zsh, because shells interpret & and some other characters specially: xdg-open 'http://example.org/site?arg1=1&arg2=2'


1

Your loop is better written as find ... | while read -r file But then you need to make sure you quote the filename inside the loop. So we end up with find /path/to/directory -type f -name *.pdf | while read -r file do gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -dQUIET -sOutputFile="new_$file" "$file" rm "$...


3

Solution using Parameter Expansion for i in *.mp3 ; do mv "$i" "${i#${i%%[!0-9 ]*}}" ; done ${i%%[!0-9 ]*} deletes from first non-digit/non-space character till end. Remaining characters are passed to ${i# which then deletes them from beginning of i variable resulting in desired file name without starting digits and space


6

I don't see why that error would occur. In fact, I am reasonably certain there were more lines to the error than you show; for one thing, there's no actual error message. However, that regular expression won't actually match either of your example files. You are using [a-z]+\.mp3 which will only match lower case letters and, since you're matching all the ...


3

Assuming a shell like bash or ksh: max_time=3 SECONDS=0 IFS=$'\n:' grep -v '^#' ref.txt | while read tag cmd; do if (( SECONDS < max_time )); then echo "starting '$cmd' (tag is '$tag')" sleep 2 # for simulation purposes else echo "did not have time to start '$cmd' (tag is '$tag')" fi done This will give the ...


1

logic to display the processes which haven't started after 180 secs. Assuming the shell is a bourne shell. I testing on bash and zsh # ... # generate a timestamp in seconds since UNIX epoch START_TIME=$(date '+%s') until [[ $(date +%s) -gt $((START_TIME + 180)) ]] do # greps for the processes running echo " N number of processes are running" #&...


2

Try using fgrep (or the -F option to grep that does the same), and write your query without escaping the "<" and ">". I'd also suggest using single-quotes ' rather than double-quotes ", since the shell may expand what it think is variables and such when you use double-quotes. fgrep -i 'template <int N>' *


0

This looks like the output of the netrw plugin. This can be disabled by entering in your ~/.vimrc file. let loaded_netrwPlugin = 1 Now if you try and edit a directory you'll get an error is a directory.


3

You can put the following lines in your vimrc to quit vim if any of its arguments are a directory: for f in argv() if isdirectory(f) echomsg "vimrc: Cowardly refusing to edit directory " . f quit endif endfor Alternatively, if you only want to quit if all arguments are directories, you can try something like this: let ndirs = 0 for f in argv()...


4

NO need for hard works, just change the /etc/bashrc file. I know, you may think that it only works on current tty but no mate, it works. Just exit once and then log in again with any user you like. You can even test this through SSHing or whatsoever. But if it didn't work - while I believe it does - read this file, this can help you much: /etc/profile


0

Your mv command doesn't work as intended because what happens is that the shell expands the wildcards and the result is a single list of file names which is passed to mv. The syntax of mv is mv SOURCE1 SOURCE2 … DESTINATION, i.e. all the arguments except the last one are file names to be moved to the destination. mv does not support pattern-based renaming. ...


4

We can walk or swim anywhere, so why do we bother with bicycles, cars, trains, boats, planes and other vehicles? Sure, walking or swimming can be tiring, but there is a huge advantage in not needed any extra equipment. For one thing, although bash is Turing-complete, it is not good at manipulating data other than integers (not too large), strings, (one-...


10

it seems Bash is a Turing-complete language The concept of Turing completeness is entirely separate from many other concepts useful in a language for programming in the large: usability, expressiveness, understandabilty, speed, etc. If Turing-completeness were all we required, we wouldn't have any programming languages at all, not even assembly language. ...


3

You can't force a shell process to use new aliases from the outside, so the request to load the new aliases will have to come from each shell instance on each terminal. You can make bash execute code after each command by putting that code in the PROMPT_COMMAND variable. So you could use something like reload_aliases () { . ~/.bash_aliases } ...


3

Some reasons not to use shell scripts for large programs, just off the top of my head: Most functions are done by forking off external commands, which is slow. In contrast, programming languages like Perl can do the equivalent of mkdir or grep internally. There's no easy way to access C libraries, or make direct system calls, which means that e.g. the ...


0

You may sanitize and validate the email address in PHP like this: $sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL); if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) { echo "This sanitized email address is considered valid.\n"; echo "Before: $email\n"; echo "After: $sanitized_email\n"; } else { echo "This sanitized ...


1

The BSD install found on OpenBSD systems has this piece of code in it (from src/usr.bin/xinstall/xinstall.c): if (!S_ISREG(to_sb.st_mode)) errc(1, EFTYPE, "%s", to_name); This emits the error install: /dev/fd/4: Inappropriate file type or format when it's discovered that /dev/df/4 is not a regular file. (There's a separate earlier check for /dev/...


1

With zsh: autoload zmv # best in ~/.zshrc zmv '[[:alnum:]](#c8).[STFWMfWM][OUAHER][0-9]' '${(L)f}' That will take of checking for potential conflicts.


16

There's often confusion between process forking and execution. When you do at the prompt of a bash shell. $ sh -c 'exec env ps' The process P1 issuing that $ prompt is currently running bash code. That bash code forks a new process P2 that executes /bin/sh which then executes /usr/bin/env, which then executes /bin/ps. So P2 has in turn executed code of ...


7

Yes, a program can know who its parent is. To illustrate, let's create two bash scripts. The first one reports its PID and starts the second script: $ cat s1.sh #!/bin/bash echo s1=$$ bash s2.sh The second script reports its process ID, the PID of its parent, and the command line used to run the parent: $ cat s2.sh #!/bin/bash echo s2=$$ PPID=$PPID ...


1

Here you are: for i in $( ls | grep [A-Z] ); do mv -f $i `echo $i | tr 'A-Z' 'a-z'`; done And this is an example showing how it works: X$ ls 123123HHHSK FILE_[1-10] DB FILE1 FILE_{1-10} SQL X$ for i in $( ls | grep [A-Z] ); do mv -f $i `echo $i | tr 'A-Z' 'a-z'`; done X$ ls 123123hhhsk file_[1-10] db file1 file_{1-10} sql EDIT: We ...


2

Whenever you want to change one class of characters into another, use tr. for f in *; do test -f "$f" && echo mv "$f" "$( tr '[:upper:]' '[:lower:]' <<<"$f" )" done The script will rename all files in the current directory to all lowercase letters. It will skip directories. Remove the echo when you're certain it does what you want. ...


1

Simple script rename-lowerfor current dir, if rename command is not working you can change in mv. #/bin/bash # script to replace all upper case to lower case for i in * do d=$(echo ${i} |tr [:upper:] [:lower:]); if [ ${d} != ${i} ] then echo "renaming:" ${i} ${d} rename ${i} ${d} ${i} # ...


2

This answer from Alex B at Stack Overflow will help you to rename both files and subfolders under a directory. It consists on using both find and rename Linux commands. I would only add that the command provided in the link above will modify directory names as well. In case that you want only to change file names, you need to change the -depth option with ...


0

This is a slightly more robust way of retrieving the HostName based on Host in the .ssh/config file. sshalias() { awk "\$1==\"Host\" {host=\$2} \$1==\"HostName\" && host==\"$1\" {print \$2}" "$HOME/.ssh/config" }


0

Appears there are two suboptimal solutions: http://serverfault.com/a/589614/70242 http://unix.stackexchange.com/a/25375/14907 Suboptimal at least when you provide input to command. Otherwise they might be both ok. script records your input and unbuffer just doesn't let you input properly. YMMV


4

I recommend you read this article. There is a big difference between shell and environment variables. PATH is one of environment ones, and is already exported (by default), so by changing it, the current shell your using and all the others - any child shells or processes - will be affected. PATH is list of directories that the system will check when ...


11

There are really two types of variable: Environment variables Shell variables To make things more complicated, they both look the same, and a shell variable can be converted to an environment variable with the export command. The env command will show the current set of environment variables. $ myvar=100 $ env | grep myvar $ export myvar $ env | grep ...


4

Try double quotes for the outer ones: sed -i "/, false);/adefine( 'WP_MEMORY_LIMIT', '64M' );"


2

For the cases where it "works", you are leaving a process running cat which is reading its standard input, which has not been closed. Since that is not (yet) closed, cat continues to run, leaving its standard output open, which is used by the shell (also not closed).


0

As has been already said, this is a "collating order" issue. The range a-z may contain upper case letters in some locales: aAbBcC[...]xXyYzZ | | from a to z The correct solution since bash 4.3 is to set the option globasciiranges: shopt -s globasciiranges to make bash act as if LC_COLLATE=C has been set in globing ...


0

Simply do: rm $(ls -I "*.txt" ) #Deletes file type except *.txt Likewise, if need to delete "except one or more file type", do: rm $(ls -I "*.txt" -I "*.pdf" ) #Deletes file types except *.txt & *.pdf


0

One possible solution from the comments is to use logger, possibly as such: ntpq -p | logger


0

Ok, I got it. I used paste to interleave svnlook youngest with ls paste <( ls | xargs -n 1 svnlook youngest) <(ls | tr " " "\n")


0

A simple solution is to use ifne command (if input not empty). In some distributions, it is not installed by default. It is a part of the package moreutils in most distros. ifne runs a given command if and only if the standard input is not empty Note that if the standard input is not empty, it is passed through ifne to the given command


0

That very much depends on the shell. If we only look at the 4 main shell families (Bourne, csh, rc, fish): Bourne family That is the Bourne shell and all its variants and ksh, bash, ash/dash, zsh, yash. var=23: that's the correct variable assignment syntax: a word that consists of unquoted letters followed by an unquoted = that appears before a command ...


0

For a 2 column output format with "dirName numFiles", where "dirName" is one of "/ /bin /usr /usr/sbin" "numFiles is the count of files in above directory being >100K You could also use : $ for i in / /bin /usr /usr/bin; do echo -en "$i " ; find $i -maxdepth 1 -size +100k | wc -l; done | column -t Example output: / 0 /bin 46 /usr ...


6

You need a space between the [ and the ! for things to work correctly. This is because [ is implemented as shell-builtin command (it even used to be a separate exectuable /usr/bin/[). You can also use: if [ ! -d "/home/unix/POSTagger2" -o ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" -o ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-...


12

You are missing some spaces, for example [! must be [ ! and "] must be " ] look to the corrected code: #!/bin/bash if [ ! -d "/home/unix/POSTagger2" ] || [ ! -d "/home/unix/POSTagger2/stanford-parser-full-2015-12-09" ] || [ ! -d "/home/unix/POSTagger2/stanford-corenlp-full-2015-12-09" ] then echo "Nope" fi Another way for your code: #!/bin/...


0

If you don't have thousands of ".sh"-files, and no sub-directories ending in ".sh", you could use: gawk -i inplace 'NR==1 && $0=="#!/bin/sh" {$0="#!/bin/bash"} 1' *.sh


1

The guide that you presented tells you how to set these variables globally - for all users. Since you only want to set these for yourself, you should put them in ~/.bashrc EDIT: As Gilles pointed out in the comment below, .bashrc is intended for interactive settings, and few things can go wrong under some circumstances. Instead, you should put them in ....


3

[[...]] is a Korn shell construct also supported by bash and zsh but otherwise not a standard sh one (and not supported by any other shell). busybox sh is based on ash that implements a subset of the POSIX specification of sh (in the POSIX locale, it is compliant for the most part) with very few extensions, and in particular, not this one. In any case, ...


0

You can use the older [ syntax if [ -n "$ENV" -a "$ENV" = 'production' ] (note I used -n rather than ! -z because it reads easier, but it's the same thing). Or we can simplify to an even older syntax by forcing the string to have a value: if [ "x$ENV" = 'xproduction' ] Finally, the -n test may not really be needed and you can possibly just do if [ "$...


3

$1,$2 … - command line positional arguments and couldn't be assigned like read [-p] $1 or any other way except set -- firsr_arg second_arg … For your case it can be test if arguments is present then test them while [ -z "$REPLY" ] ; do if [ -z "$1" ] ; then read -p "Do you want to continue?(yes/no) " else REPLY=$1 set -...



Top 50 recent answers are included