QuestionId
stringlengths 3
8
| QuestionTitle
stringlengths 15
149
| QuestionScore
int64 1
27.2k
| QuestionCreatedUtc
stringdate 2008-08-01 18:33:08
2025-06-16 04:59:48
| QuestionBodyHtml
stringlengths 40
28.2k
| QuestionViewCount
int64 78
16.5M
| QuestionOwnerUserId
float64 4
25.2M
⌀ | QuestionLastActivityUtc
stringdate 2008-09-08 19:26:01
2026-01-24 22:40:25
| AcceptedAnswerId
int64 266
79.7M
| AnswerScore
int64 2
30.1k
| AnswerCreatedUtc
stringdate 2008-08-01 23:40:28
2025-06-16 05:23:39
| AnswerOwnerUserId
float64 1
29.5M
⌀ | AnswerLastActivityUtc
stringdate 2008-08-01 23:40:28
2026-01-23 17:46:09
| QuestionLink
stringlengths 31
36
| AnswerLink
stringlengths 31
36
| AnswerBodyHtml
stringlengths 35
33k
| AnswerBodyPreview
stringlengths 35
400
| AllTagIdsCsv
stringlengths 2
37
| AllTagNamesCsv
stringlengths 2
106
| MergedQuestion
stringlengths 74
28.4k
| quality_filter
stringclasses 10
values | unique_id
int64 0
29k
| tag_major_lang
stringclasses 10
values | MergedQuestion_md
stringlengths 60
28.1k
| AnswerBodyHtml_md
stringlengths 14
29.2k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
59895
|
How do I get the directory where a Bash script is located from within the script itself?
| 6,405
|
2008-09-12 20:39:56
|
<p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p>
<p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p>
<pre><code>$ ./application
</code></pre>
| 2,834,402
| 2,908
|
2025-06-10 04:21:43
| 246,128
| 8,291
|
2008-10-29 08:36:45
| 7,412
|
2025-05-22 03:57:59
|
https://stackoverflow.com/q/59895
|
https://stackoverflow.com/a/246128
|
<pre><code>#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
</code></pre>
<p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p>
<p>It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:</p>
<pre><code>#!/usr/bin/env bash
get_script_dir()
{
local SOURCE_PATH="${BASH_SOURCE[0]}"
local SYMLINK_DIR
local SCRIPT_DIR
# Resolve symlinks recursively
while [ -L "$SOURCE_PATH" ]; do
# Get symlink directory
SYMLINK_DIR="$( cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd )"
# Resolve symlink target (relative or absolute)
SOURCE_PATH="$(readlink "$SOURCE_PATH")"
# Check if candidate path is relative or absolute
if [[ $SOURCE_PATH != /* ]]; then
# Candidate path is relative, resolve to full path
SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH
fi
done
# Get final script directory path from fully resolved source path
SCRIPT_DIR="$(cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd)"
echo "$SCRIPT_DIR"
}
echo "get_script_dir: $(get_script_dir)"
</code></pre>
<p>This last one will work with any combination of aliases, <code>source</code>, <code>bash -c</code>, symlinks, etc.</p>
<p><strong>Beware:</strong> if you <code>cd</code> to a different directory before running this snippet, the result may be incorrect!</p>
<p>Also, watch out for <a href="http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/" rel="noreferrer"><code>$CDPATH</code> gotchas</a>, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling <code>update_terminal_cwd >&2</code> on Mac). Adding <code>>/dev/null 2>&1</code> at the end of your <code>cd</code> command will take care of both possibilities.</p>
<p>To understand how it works, try running this more verbose form:</p>
<pre><code>#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
</code></pre>
<p>And it will print something like:</p>
<pre class="lang-none prettyprint-override"><code>SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
</code></pre>
|
<pre><code>#!/usr/bin/env bash SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) </code></pre> <p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p> <p>It will work as long as the last component of the path used to find the script is not a symlink (directory l
|
218, 387
|
bash, directory
|
<h1>How do I get the directory where a Bash script is located from within the script itself?</h1>
<p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p>
<p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p>
<pre><code>$ ./application
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 16
|
bash
|
# How do I get the directory where a Bash script is located from within the script itself?
How do I get the path of the directory in which a [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) script is located, *inside* that script?
I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:
```
$ ./application
```
|
```
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
```
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
```
#!/usr/bin/env bash
get_script_dir()
{
local SOURCE_PATH="${BASH_SOURCE[0]}"
local SYMLINK_DIR
local SCRIPT_DIR
# Resolve symlinks recursively
while [ -L "$SOURCE_PATH" ]; do
# Get symlink directory
SYMLINK_DIR="$( cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd )"
# Resolve symlink target (relative or absolute)
SOURCE_PATH="$(readlink "$SOURCE_PATH")"
# Check if candidate path is relative or absolute
if [[ $SOURCE_PATH != /* ]]; then
# Candidate path is relative, resolve to full path
SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH
fi
done
# Get final script directory path from fully resolved source path
SCRIPT_DIR="$(cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd)"
echo "$SCRIPT_DIR"
}
echo "get_script_dir: $(get_script_dir)"
```
This last one will work with any combination of aliases, `source`, `bash -c`, symlinks, etc.
**Beware:** if you `cd` to a different directory before running this snippet, the result may be incorrect!
Also, watch out for [`$CDPATH` gotchas](http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/), and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling `update_terminal_cwd >&2` on Mac). Adding `>/dev/null 2>&1` at the end of your `cd` command will take care of both possibilities.
To understand how it works, try running this more verbose form:
```
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
```
And it will print something like:
```
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
```
|
11304895
|
How do I copy a folder from remote to local using scp?
| 3,597
|
2012-07-03 05:17:58
|
<p>How do I copy a folder from remote to local host using <code>scp</code>?</p>
<p>I use <code>ssh</code> to log in to my server.<br />
Then, I would like to copy the remote folder <code>foo</code> to local <code>/home/user/Desktop</code>.</p>
<p>How do I achieve this?</p>
| 3,900,240
| 1,469,282
|
2024-09-17 16:05:15
| 11,304,926
| 6,406
|
2012-07-03 05:21:39
| 774,116
|
2020-10-15 01:21:14
|
https://stackoverflow.com/q/11304895
|
https://stackoverflow.com/a/11304926
|
<pre><code>scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/
</code></pre>
<p>By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.</p>
<p>From <code>man scp</code> (See <a href="http://man7.org/linux/man-pages/man1/scp.1.html" rel="noreferrer">online manual</a>)</p>
<blockquote>
<p>-r Recursively copy entire directories</p>
</blockquote>
|
<pre><code>scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/ </code></pre> <p>By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.</p> <p>From <code>man scp</code> (See <a href="http://man7.org/linux/man-pages/man1/scp.1.html" rel="noreferrer">online manual</a>)</p> <blockquo
|
386, 390, 1231, 3149, 4330
|
command-line, copy, scp, shell, ssh
|
<h1>How do I copy a folder from remote to local using scp?</h1>
<p>How do I copy a folder from remote to local host using <code>scp</code>?</p>
<p>I use <code>ssh</code> to log in to my server.<br />
Then, I would like to copy the remote folder <code>foo</code> to local <code>/home/user/Desktop</code>.</p>
<p>How do I achieve this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 17
|
bash
|
# How do I copy a folder from remote to local using scp?
How do I copy a folder from remote to local host using `scp`?
I use `ssh` to log in to my server.
Then, I would like to copy the remote folder `foo` to local `/home/user/Desktop`.
How do I achieve this?
|
```
scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/
```
By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.
From `man scp` (See [online manual](http://man7.org/linux/man-pages/man1/scp.1.html))
> -r Recursively copy entire directories
|
59838
|
How do I check if a directory exists or not in a Bash shell script?
| 4,553
|
2008-09-12 20:06:25
|
<p>What command checks if a directory exists or not within a Bash shell script?</p>
| 3,495,129
| 4,120
|
2023-12-23 06:16:55
| 59,839
| 6,152
|
2008-09-12 20:07:06
| 4,120
|
2022-08-01 01:21:58
|
https://stackoverflow.com/q/59838
|
https://stackoverflow.com/a/59839
|
<p>To check if a directory exists:</p>
<pre><code>if [ -d "$DIRECTORY" ]; then
echo "$DIRECTORY does exist."
fi
</code></pre>
<p>To check if a directory does not exist:</p>
<pre><code>if [ ! -d "$DIRECTORY" ]; then
echo "$DIRECTORY does not exist."
fi
</code></pre>
<hr />
<p>However, as <a href="https://stackoverflow.com/users/1438/jon-ericson">Jon Ericson</a> points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.
E.g. running this:</p>
<pre><code>ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
</code></pre>
<p>Will produce the error message:</p>
<pre class="lang-none prettyprint-override"><code>rmdir: failed to remove `symlink': Not a directory
</code></pre>
<p>So symbolic links may have to be treated differently, if subsequent commands expect directories:</p>
<pre><code>if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here.
rmdir "$LINK_OR_DIR"
fi
fi
</code></pre>
<hr />
<p>Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean <a href="https://stackoverflow.com/a/67458/102401">in another answer</a>.</p>
<p>If the variables contain spaces or other unusual characters it will probably cause the script to fail.</p>
|
<p>To check if a directory exists:</p> <pre><code>if [ -d "$DIRECTORY" ]; then echo "$DIRECTORY does exist." fi </code></pre> <p>To check if a directory does not exist:</p> <pre><code>if [ ! -d "$DIRECTORY" ]; then echo "$DIRECTORY does not exist." fi </code></pre> <hr /> <p>However, as <a href="https://stackoverflow.com/users/1438/jon-ericson">Jon Erics
|
34, 387, 390, 1796, 1993
|
bash, command, posix, shell, unix
|
<h1>How do I check if a directory exists or not in a Bash shell script?</h1>
<p>What command checks if a directory exists or not within a Bash shell script?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 18
|
bash
|
# How do I check if a directory exists or not in a Bash shell script?
What command checks if a directory exists or not within a Bash shell script?
|
To check if a directory exists:
```
if [ -d "$DIRECTORY" ]; then
echo "$DIRECTORY does exist."
fi
```
To check if a directory does not exist:
```
if [ ! -d "$DIRECTORY" ]; then
echo "$DIRECTORY does not exist."
fi
```
---
However, as [Jon Ericson](https://stackoverflow.com/users/1438/jon-ericson) points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.
E.g. running this:
```
ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
```
Will produce the error message:
```
rmdir: failed to remove `symlink': Not a directory
```
So symbolic links may have to be treated differently, if subsequent commands expect directories:
```
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here.
rmdir "$LINK_OR_DIR"
fi
fi
```
---
Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean [in another answer](https://stackoverflow.com/a/67458/102401).
If the variables contain spaces or other unusual characters it will probably cause the script to fail.
|
89228
|
How do I execute a program or call a system command?
| 6,282
|
2008-09-18 01:35:30
|
<p>How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>
| 5,200,895
| 17,085
|
2025-11-04 02:52:45
| 89,243
| 5,961
|
2008-09-18 01:39:35
| 11,465
|
2023-05-19 23:52:54
|
https://stackoverflow.com/q/89228
|
https://stackoverflow.com/a/89243
|
<p>Use <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>import subprocess
subprocess.run(["ls", "-l"])
</code></pre>
<p>Another common way is <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also <code>subprocess.run</code> is generally more flexible (you can get the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout" rel="noreferrer"><code>stdout</code></a>, <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr" rel="noreferrer"><code>stderr</code></a>, the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode" rel="noreferrer">"real" status code</a>, better <a href="https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError" rel="noreferrer">error handling</a>, etc.). Even the <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer">documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead.</p>
<p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p>
<pre class="lang-py prettyprint-override"><code>subprocess.call(["ls", "-l"])
</code></pre>
|
<p>Use <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.run(["ls", "-l"]) </code></pre> <p>Another common way is <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> but yo
|
16, 390, 391, 1796, 2348
|
command, python, shell, subprocess, terminal
|
<h1>How do I execute a program or call a system command?</h1>
<p>How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 19
|
bash
|
# How do I execute a program or call a system command?
How do I call an external command within Python as if I had typed it in a shell or command prompt?
|
Use [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run):
```
import subprocess
subprocess.run(["ls", "-l"])
```
Another common way is [`os.system`](https://docs.python.org/library/os.html#os.system) but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also `subprocess.run` is generally more flexible (you can get the [`stdout`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout), [`stderr`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr), the ["real" status code](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode), better [error handling](https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError), etc.). Even the [documentation for `os.system`](https://docs.python.org/library/os.html#os.system) recommends using `subprocess` instead.
On Python 3.4 and earlier, use `subprocess.call` instead of `.run`:
```
subprocess.call(["ls", "-l"])
```
|
638975
|
How do I tell if a file does not exist in Bash?
| 4,162
|
2009-03-12 14:48:43
|
<p>This checks if a file exists:</p>
<pre><code>#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
</code></pre>
<p>How do I only check if the file does <strong>not</strong> exist?</p>
| 3,439,075
| 1,288
|
2024-06-18 10:32:34
| 638,980
| 5,614
|
2009-03-12 14:50:01
| 75,170
|
2022-07-17 00:26:03
|
https://stackoverflow.com/q/638975
|
https://stackoverflow.com/a/638980
|
<p>The <a href="http://man7.org/linux/man-pages/man1/test.1.html" rel="noreferrer"><code>test</code></a> command (written as <code>[</code> here) has a "not" logical operator, <code>!</code> (exclamation mark):</p>
<pre><code>if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
</code></pre>
|
<p>The <a href="http://man7.org/linux/man-pages/man1/test.1.html" rel="noreferrer"><code>test</code></a> command (written as <code>[</code> here) has a "not" logical operator, <code>!</code> (exclamation mark):</p> <pre><code>if [ ! -f /tmp/foo.txt ]; then echo "File not found!" fi </code></pre>
|
387, 531, 724
|
bash, file-io, scripting
|
<h1>How do I tell if a file does not exist in Bash?</h1>
<p>This checks if a file exists:</p>
<pre><code>#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
</code></pre>
<p>How do I only check if the file does <strong>not</strong> exist?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 20
|
bash
|
# How do I tell if a file does not exist in Bash?
This checks if a file exists:
```
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
echo "File $FILE exists."
else
echo "File $FILE does not exist."
fi
```
How do I only check if the file does **not** exist?
|
The [`test`](http://man7.org/linux/man-pages/man1/test.1.html) command (written as `[` here) has a "not" logical operator, `!` (exclamation mark):
```
if [ ! -f /tmp/foo.txt ]; then
echo "File not found!"
fi
```
|
229551
|
How to check if a string contains a substring in Bash
| 3,658
|
2008-10-23 12:37:31
|
<p>I have a string in Bash:</p>
<pre class="lang-sh prettyprint-override"><code>string="My string"
</code></pre>
<p>How can I test if it contains another string?</p>
<pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
</code></pre>
<p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p>
<pre class="lang-sh prettyprint-override"><code>if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
</code></pre>
<p>That looks a bit clumsy.</p>
| 3,391,086
| 30,773
|
2026-01-08 11:58:40
| 229,606
| 5,028
|
2008-10-23 12:55:24
| 21,632
|
2020-04-17 01:20:42
|
https://stackoverflow.com/q/229551
|
https://stackoverflow.com/a/229606
|
<p>You can use <a href="https://stackoverflow.com/a/229585/3755692">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p>
<pre><code>string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
</code></pre>
<p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should be outside. Also note that a simple comparison operator is used (i.e. <code>==</code>), not the regex operator <code>=~</code>.</p>
|
<p>You can use <a href="https://stackoverflow.com/a/229585/3755692">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p> <pre><code>string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fi </code></pre> <p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should
|
139, 387, 390, 4371, 10327
|
bash, sh, shell, string, substring
|
<h1>How to check if a string contains a substring in Bash</h1>
<p>I have a string in Bash:</p>
<pre class="lang-sh prettyprint-override"><code>string="My string"
</code></pre>
<p>How can I test if it contains another string?</p>
<pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
</code></pre>
<p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p>
<pre class="lang-sh prettyprint-override"><code>if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
</code></pre>
<p>That looks a bit clumsy.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 21
|
bash
|
# How to check if a string contains a substring in Bash
I have a string in Bash:
```
string="My string"
```
How can I test if it contains another string?
```
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
```
Where `??` is my unknown operator. Do I use `echo` and `grep`?
```
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
```
That looks a bit clumsy.
|
You can use [Marcus's answer (* wildcards)](https://stackoverflow.com/a/229585/3755692) outside a case statement, too, if you use double brackets:
```
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
```
Note that spaces in the needle string need to be placed between double quotes, and the `*` wildcards should be outside. Also note that a simple comparison operator is used (i.e. `==`), not the regex operator `=~`.
|
4181703
|
How to concatenate string variables in Bash
| 3,611
|
2010-11-15 05:38:35
|
<p>In PHP, strings are concatenated together as follows:</p>
<pre><code>$foo = "Hello";
$foo .= " World";
</code></pre>
<p>Here, <code>$foo</code> becomes <code>"Hello World"</code>.</p>
<p>How is this accomplished in Bash?</p>
| 5,351,453
| 170,365
|
2025-10-16 09:01:13
| 4,181,721
| 4,890
|
2010-11-15 05:41:36
| 227,665
|
2019-09-01 12:51:28
|
https://stackoverflow.com/q/4181703
|
https://stackoverflow.com/a/4181721
|
<pre><code>foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World
</code></pre>
<p>In general to concatenate two variables you can just write them one after another:</p>
<pre><code>a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World
</code></pre>
|
<pre><code>foo="Hello" foo="${foo} World" echo "${foo}" > Hello World </code></pre> <p>In general to concatenate two variables you can just write them one after another:</p> <pre><code>a='Hello' b='World' c="${a} ${b}" echo "${c}" > Hello World </code></pre>
|
367, 387, 390, 6050, 7792
|
bash, concatenation, shell, string-concatenation, syntax
|
<h1>How to concatenate string variables in Bash</h1>
<p>In PHP, strings are concatenated together as follows:</p>
<pre><code>$foo = "Hello";
$foo .= " World";
</code></pre>
<p>Here, <code>$foo</code> becomes <code>"Hello World"</code>.</p>
<p>How is this accomplished in Bash?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 22
|
bash
|
# How to concatenate string variables in Bash
In PHP, strings are concatenated together as follows:
```
$foo = "Hello";
$foo .= " World";
```
Here, `$foo` becomes `"Hello World"`.
How is this accomplished in Bash?
|
```
foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World
```
In general to concatenate two variables you can just write them one after another:
```
a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World
```
|
793858
|
How to mkdir only if a directory does not already exist?
| 2,998
|
2009-04-27 14:47:44
|
<p>I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the <code>mkdir</code> command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that <code>mkdir</code> throws when it tries to create an existing directory. </p>
<p>How can I best do this?</p>
| 2,292,191
| 73,371
|
2023-03-17 09:06:20
| 793,867
| 4,852
|
2009-04-27 14:49:46
| 69,755
|
2019-01-23 21:04:22
|
https://stackoverflow.com/q/793858
|
https://stackoverflow.com/a/793867
|
<p>Try <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html" rel="noreferrer"><code>mkdir -p</code></a>:</p>
<pre><code>mkdir -p foo
</code></pre>
<p>Note that this will also create any intermediate directories that don't exist; for instance,</p>
<pre><code>mkdir -p foo/bar/baz
</code></pre>
<p>will create directories <code>foo</code>, <code>foo/bar</code>, and <code>foo/bar/baz</code> if they don't exist.</p>
<p>Some implementation like GNU <code>mkdir</code> include <code>mkdir --parents</code> as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.</p>
<p>If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/test.html" rel="noreferrer"><code>test</code></a> for the existence of the directory first:</p>
<pre><code>[ -d foo ] || mkdir foo
</code></pre>
|
<p>Try <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html" rel="noreferrer"><code>mkdir -p</code></a>:</p> <pre><code>mkdir -p foo </code></pre> <p>Note that this will also create any intermediate directories that don't exist; for instance,</p> <pre><code>mkdir -p foo/bar/baz </code></pre> <p>will create directories <code>foo</code>, <code>foo/bar</code>, and <code>fo
|
390, 531, 989, 1964, 24423
|
aix, ksh, mkdir, scripting, shell
|
<h1>How to mkdir only if a directory does not already exist?</h1>
<p>I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the <code>mkdir</code> command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that <code>mkdir</code> throws when it tries to create an existing directory. </p>
<p>How can I best do this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 23
|
bash
|
# How to mkdir only if a directory does not already exist?
I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the `mkdir` command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that `mkdir` throws when it tries to create an existing directory.
How can I best do this?
|
Try [`mkdir -p`](http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html):
```
mkdir -p foo
```
Note that this will also create any intermediate directories that don't exist; for instance,
```
mkdir -p foo/bar/baz
```
will create directories `foo`, `foo/bar`, and `foo/bar/baz` if they don't exist.
Some implementation like GNU `mkdir` include `mkdir --parents` as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.
If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can [`test`](http://www.opengroup.org/onlinepubs/009695399/utilities/test.html) for the existence of the directory first:
```
[ -d foo ] || mkdir foo
```
|
592620
|
How can I check if a program exists from a Bash script?
| 3,215
|
2009-02-26 21:52:49
|
<p>How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?</p>
<p>It seems like it should be easy, but it's been stumping me.</p>
| 1,298,786
| 2,687
|
2025-06-01 11:10:42
| 677,212
| 4,596
|
2009-03-24 12:45:20
| 58,803
|
2025-06-01 11:10:42
|
https://stackoverflow.com/q/592620
|
https://stackoverflow.com/a/677212
|
<h2>Answer</h2>
<p>POSIX compatible:</p>
<pre><code>command -v <the_command>
</code></pre>
<p>Example use:</p>
<pre><code>if ! command -v <the_command> >/dev/null 2>&1
then
echo "<the_command> could not be found"
exit 1
fi
</code></pre>
<p>For Bash specific environments:</p>
<pre><code>hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
</code></pre>
<h2>Explanation</h2>
<p>Avoid <code>which</code>. Not only is it an external process you're launching for doing very little (meaning builtins like <code>hash</code>, <code>type</code> or <code>command</code> are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.</p>
<p>Why care?</p>
<ul>
<li>Many operating systems have a <code>which</code> that <strong>doesn't even set an exit status</strong>, meaning the <code>if which foo</code> won't even work there and will <strong>always</strong> report that <code>foo</code> exists, even if it doesn't (note that some POSIX shells appear to do this for <code>hash</code> too).</li>
<li>Many operating systems make <code>which</code> do custom and evil stuff like change the output or even hook into the package manager.</li>
</ul>
<p>So, don't use <code>which</code>. Instead use one of these:</p>
<pre><code>command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<pre><code>type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<pre><code>hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<p>(Minor side-note: some will suggest <code>2>&-</code> is the same <code>2>/dev/null</code> but shorter – <em>this is untrue</em>. <code>2>&-</code> closes FD 2 which causes an <strong>error</strong> in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))<br />
(Additional minor side-note: some will suggest <code>&>/dev/null</code>, but this <a href="https://www.shellcheck.net/wiki/SC3020" rel="noreferrer">is not POSIX compliant</a>)</p>
<p>If your hash bang is <code>/bin/sh</code> then you should care about what POSIX says. <code>type</code> and <code>hash</code>'s exit codes aren't terribly well defined by POSIX, and <code>hash</code> is seen to exit successfully when the command doesn't exist (haven't seen this with <code>type</code> yet). <code>command</code>'s exit status is well defined by POSIX, so that one is probably the safest to use.</p>
<p>If your script uses <code>bash</code> though, POSIX rules don't really matter anymore and both <code>type</code> and <code>hash</code> become perfectly safe to use. <code>type</code> now has a <code>-P</code> to search just the <code>PATH</code> and <code>hash</code> has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.</p>
<p>As a simple example, here's a function that runs <code>gdate</code> if it exists, otherwise <code>date</code>:</p>
<pre><code>gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
</code></pre>
|
<h2>Answer</h2> <p>POSIX compatible:</p> <pre><code>command -v <the_command> </code></pre> <p>Example use:</p> <pre><code>if ! command -v <the_command> >/dev/null 2>&1 then echo "<the_command> could not be found" exit 1 fi </code></pre> <p>For Bash specific environments:</p> <pre><code>hash <the_command> # For regular commands. Or... type <the
|
387
|
bash
|
<h1>How can I check if a program exists from a Bash script?</h1>
<p>How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?</p>
<p>It seems like it should be easy, but it's been stumping me.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 24
|
bash
|
# How can I check if a program exists from a Bash script?
How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?
It seems like it should be easy, but it's been stumping me.
|
## Answer
POSIX compatible:
```
command -v <the_command>
```
Example use:
```
if ! command -v <the_command> >/dev/null 2>&1
then
echo "<the_command> could not be found"
exit 1
fi
```
For Bash specific environments:
```
hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
```
## Explanation
Avoid `which`. Not only is it an external process you're launching for doing very little (meaning builtins like `hash`, `type` or `command` are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.
Why care?
- Many operating systems have a `which` that **doesn't even set an exit status**, meaning the `if which foo` won't even work there and will **always** report that `foo` exists, even if it doesn't (note that some POSIX shells appear to do this for `hash` too).
- Many operating systems make `which` do custom and evil stuff like change the output or even hook into the package manager.
So, don't use `which`. Instead use one of these:
```
command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
```
```
type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
```
```
hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
```
(Minor side-note: some will suggest `2>&-` is the same `2>/dev/null` but shorter – *this is untrue*. `2>&-` closes FD 2 which causes an **error** in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
(Additional minor side-note: some will suggest `&>/dev/null`, but this [is not POSIX compliant](https://www.shellcheck.net/wiki/SC3020))
If your hash bang is `/bin/sh` then you should care about what POSIX says. `type` and `hash`'s exit codes aren't terribly well defined by POSIX, and `hash` is seen to exit successfully when the command doesn't exist (haven't seen this with `type` yet). `command`'s exit status is well defined by POSIX, so that one is probably the safest to use.
If your script uses `bash` though, POSIX rules don't really matter anymore and both `type` and `hash` become perfectly safe to use. `type` now has a `-P` to search just the `PATH` and `hash` has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.
As a simple example, here's a function that runs `gdate` if it exists, otherwise `date`:
```
gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
```
|
965053
|
Extract filename and extension in Bash
| 2,918
|
2009-06-08 14:00:29
|
<p>I want to get the filename (without extension) and the extension separately.</p>
<p>The best solution I found so far is:</p>
<pre><code>NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
</code></pre>
<p>This is wrong because it doesn't work if the file name contains multiple <code>.</code> characters. If, let's say, I have <code>a.b.js</code>, it will consider <code>a</code> and <code>b.js</code>, instead of <code>a.b</code> and <code>js</code>.</p>
<p>It can be easily done in Python with</p>
<pre class="lang-py prettyprint-override"><code>file, ext = os.path.splitext(path)
</code></pre>
<p>but I'd prefer not to fire up a Python interpreter just for this, if possible.</p>
<p>Any better ideas?</p>
| 2,427,384
| 5,475
|
2025-08-17 16:24:24
| 965,072
| 4,538
|
2009-06-08 14:05:19
| 17,833
|
2025-03-21 07:22:40
|
https://stackoverflow.com/q/965053
|
https://stackoverflow.com/a/965072
|
<p>First, get file name without the path:</p>
<pre class="lang-bash prettyprint-override"><code>filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
</code></pre>
<p>Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:</p>
<pre class="lang-bash prettyprint-override"><code>filename="${fullfile##*/}"
</code></pre>
<p>You may want to check the documentation :</p>
<ul>
<li>On the web at section "<a href="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">3.5.3 Shell Parameter Expansion</a>"</li>
<li>In the bash manpage at section called "Parameter Expansion"</li>
</ul>
|
<p>First, get file name without the path:</p> <pre class="lang-bash prettyprint-override"><code>filename=$(basename -- "$fullfile") extension="${filename##*.}" filename="${filename%.*}" </code></pre> <p>Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:</p> <pre class="lang-bash
|
139, 387, 1062
|
bash, filenames, string
|
<h1>Extract filename and extension in Bash</h1>
<p>I want to get the filename (without extension) and the extension separately.</p>
<p>The best solution I found so far is:</p>
<pre><code>NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
</code></pre>
<p>This is wrong because it doesn't work if the file name contains multiple <code>.</code> characters. If, let's say, I have <code>a.b.js</code>, it will consider <code>a</code> and <code>b.js</code>, instead of <code>a.b</code> and <code>js</code>.</p>
<p>It can be easily done in Python with</p>
<pre class="lang-py prettyprint-override"><code>file, ext = os.path.splitext(path)
</code></pre>
<p>but I'd prefer not to fire up a Python interpreter just for this, if possible.</p>
<p>Any better ideas?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 25
|
bash
|
# Extract filename and extension in Bash
I want to get the filename (without extension) and the extension separately.
The best solution I found so far is:
```
NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
```
This is wrong because it doesn't work if the file name contains multiple `.` characters. If, let's say, I have `a.b.js`, it will consider `a` and `b.js`, instead of `a.b` and `js`.
It can be easily done in Python with
```
file, ext = os.path.splitext(path)
```
but I'd prefer not to fire up a Python interpreter just for this, if possible.
Any better ideas?
|
First, get file name without the path:
```
filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
```
Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:
```
filename="${fullfile##*/}"
```
You may want to check the documentation :
- On the web at section "[3.5.3 Shell Parameter Expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)"
- In the bash manpage at section called "Parameter Expansion"
|
5905054
|
How can I recursively find all files in current and subfolders based on wildcard matching?
| 3,144
|
2011-05-05 23:01:34
|
<p>How can I recursively find all files in current and subfolders based on wildcard matching?</p>
| 5,129,961
| 302,064
|
2023-12-29 09:16:26
| 5,905,066
| 4,478
|
2011-05-05 23:03:37
| 82,219
|
2023-12-29 09:16:26
|
https://stackoverflow.com/q/5905054
|
https://stackoverflow.com/a/5905066
|
<p>Use <a href="http://linux.die.net/man/1/find" rel="noreferrer"><code>find</code></a>:</p>
<pre><code>find . -name "foo*"
</code></pre>
<p><code>find</code> needs a starting point, so the <code>.</code> (dot) points to the current directory.</p>
<p>If you need <strong>case insensitive</strong> search use :</p>
<pre><code>find . -iname "foo*"
</code></pre>
|
<p>Use <a href="http://linux.die.net/man/1/find" rel="noreferrer"><code>find</code></a>:</p> <pre><code>find . -name "foo*" </code></pre> <p><code>find</code> needs a starting point, so the <code>.</code> (dot) points to the current directory.</p> <p>If you need <strong>case insensitive</strong> search use :</p> <pre><code>find . -iname "foo*" </code></pre>
|
58, 390
|
linux, shell
|
<h1>How can I recursively find all files in current and subfolders based on wildcard matching?</h1>
<p>How can I recursively find all files in current and subfolders based on wildcard matching?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 26
|
bash
|
# How can I recursively find all files in current and subfolders based on wildcard matching?
How can I recursively find all files in current and subfolders based on wildcard matching?
|
Use [`find`](http://linux.die.net/man/1/find):
```
find . -name "foo*"
```
`find` needs a starting point, so the `.` (dot) points to the current directory.
If you need **case insensitive** search use :
```
find . -iname "foo*"
```
|
8467424
|
Echo newline in Bash prints literal \n
| 3,667
|
2011-12-11 21:01:54
|
<p>How do I print a newline? This merely prints <code>\n</code>:</p>
<pre><code>echo -e "Hello,\nWorld!"
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Hello,\nWorld!
</code></pre>
| 3,688,424
| 187,644
|
2025-12-09 22:55:19
| 8,467,449
| 4,311
|
2011-12-11 21:04:56
| 56,338
|
2025-07-16 17:42:38
|
https://stackoverflow.com/q/8467424
|
https://stackoverflow.com/a/8467449
|
<p>Use <code>printf</code> instead:</p>
<pre><code>printf 'Hello, \nWorld!\n'
</code></pre>
<p><code>printf</code> behaves more consistently across different environments than <code>echo</code>.</p>
|
<p>Use <code>printf</code> instead:</p> <pre><code>printf 'Hello, \nWorld!\n' </code></pre> <p><code>printf</code> behaves more consistently across different environments than <code>echo</code>.</p>
|
387, 3705, 13824
|
bash, echo, newline
|
<h1>Echo newline in Bash prints literal \n</h1>
<p>How do I print a newline? This merely prints <code>\n</code>:</p>
<pre><code>echo -e "Hello,\nWorld!"
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Hello,\nWorld!
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 27
|
bash
|
# Echo newline in Bash prints literal \n
How do I print a newline? This merely prints `\n`:
```
echo -e "Hello,\nWorld!"
```
Output:
```
Hello,\nWorld!
```
|
Use `printf` instead:
```
printf 'Hello, \nWorld!\n'
```
`printf` behaves more consistently across different environments than `echo`.
|
1825585
|
Determine installed PowerShell version
| 2,915
|
2009-12-01 11:30:03
|
<p>How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?</p>
| 3,250,810
| 35,483
|
2025-11-15 13:22:28
| 1,825,807
| 3,878
|
2009-12-01 12:12:38
| null |
2020-01-02 07:33:10
|
https://stackoverflow.com/q/1825585
|
https://stackoverflow.com/a/1825807
|
<p>Use <code>$PSVersionTable.PSVersion</code> to determine the engine version. If the variable does not exist, it is safe to assume the engine is version <code>1.0</code>.</p>
<p>Note that <code>$Host.Version</code> and <code>(Get-Host).Version</code> are not reliable - they reflect
the version of the host only, not the engine. PowerGUI,
PowerShellPLUS, etc. are all hosting applications, and
they will set the host's version to reflect their product
version — which is entirely correct, but not what you're looking for.</p>
<pre><code>PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
</code></pre>
|
<p>Use <code>$PSVersionTable.PSVersion</code> to determine the engine version. If the variable does not exist, it is safe to assume the engine is version <code>1.0</code>.</p> <p>Note that <code>$Host.Version</code> and <code>(Get-Host).Version</code> are not reliable - they reflect the version of the host only, not the engine. PowerGUI, PowerShellPLUS, etc. are all hosting applications, and they
|
526, 5792
|
powershell, version
|
<h1>Determine installed PowerShell version</h1>
<p>How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 28
|
bash
|
# Determine installed PowerShell version
How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?
|
Use `$PSVersionTable.PSVersion` to determine the engine version. If the variable does not exist, it is safe to assume the engine is version `1.0`.
Note that `$Host.Version` and `(Get-Host).Version` are not reliable - they reflect
the version of the host only, not the engine. PowerGUI,
PowerShellPLUS, etc. are all hosting applications, and
they will set the host's version to reflect their product
version — which is entirely correct, but not what you're looking for.
```
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
```
|
192249
|
How do I parse command line arguments in Bash?
| 2,627
|
2008-10-10 16:57:19
|
<p>Say, I have a script that gets called with this line:</p>
<pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile
</code></pre>
<p>or this one:</p>
<pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile
</code></pre>
<p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
| 2,195,200
| 1,512
|
2025-05-30 12:27:53
| 14,203,146
| 3,687
|
2013-01-07 20:01:05
| 117,471
|
2024-03-18 06:12:10
|
https://stackoverflow.com/q/192249
|
https://stackoverflow.com/a/14203146
|
<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4>
<pre class="lang-bash prettyprint-override"><code>cat >/tmp/demo-space-separated.sh <<'EOF'
#!/bin/bash
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-e|--extension)
EXTENSION="$2"
shift # past argument
shift # past value
;;
-s|--searchpath)
SEARCHPATH="$2"
shift # past argument
shift # past value
;;
--default)
DEFAULT=YES
shift # past argument
;;
-*|--*)
echo "Unknown option $1"
exit 1
;;
*)
POSITIONAL_ARGS+=("$1") # save positional arg
shift # past argument
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 "$1"
fi
EOF
chmod +x /tmp/demo-space-separated.sh
/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-bash prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<hr />
<h4>Bash Equals-Separated (e.g., <code>--option=argument</code>)</h4>
<pre class="lang-bash prettyprint-override"><code>cat >/tmp/demo-equals-separated.sh <<'EOF'
#!/bin/bash
for i in "$@"; do
case $i in
-e=*|--extension=*)
EXTENSION="${i#*=}"
shift # past argument=value
;;
-s=*|--searchpath=*)
SEARCHPATH="${i#*=}"
shift # past argument=value
;;
--default)
DEFAULT=YES
shift # past argument with no value
;;
-*|--*)
echo "Unknown option $i"
exit 1
;;
*)
;;
esac
done
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 $1
fi
EOF
chmod +x /tmp/demo-equals-separated.sh
/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-bash prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<hr />
<p>To better understand <code>${i#*=}</code> search for "Substring Removal" in <a href="http://tldp.org/LDP/abs/html/string-manipulation.html" rel="noreferrer">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' <<< "$i"`</code> which calls a needless subprocess or <code>`echo "$i" | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p>
<hr />
<h4>Using bash with getopt[s]</h4>
<p>getopt(1) limitations (older, relatively-recent <code>getopt</code> versions):</p>
<ul>
<li>can't handle arguments that are empty strings</li>
<li>can't handle arguments with embedded whitespace</li>
</ul>
<p>More recent <code>getopt</code> versions don't have these limitations. For more information, see these <a href="https://mywiki.wooledge.org/BashFAQ/035#getopts" rel="noreferrer">docs</a>.</p>
<hr />
<h4>POSIX getopts</h4>
<p>Additionally, the POSIX shell and others offer <code>getopts</code> which doen't have these limitations. I've included a simplistic <code>getopts</code> example.</p>
<pre class="lang-bash prettyprint-override"><code>cat >/tmp/demo-getopts.sh <<'EOF'
#!/bin/sh
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize our own variables:
output_file=""
verbose=0
while getopts "h?vf:" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v) verbose=1
;;
f) output_file=$OPTARG
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
echo "verbose=$verbose, output_file='$output_file', Leftovers: $@"
EOF
chmod +x /tmp/demo-getopts.sh
/tmp/demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-bash prettyprint-override"><code>verbose=1, output_file='/etc/hosts', Leftovers: foo bar
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<p>The advantages of <code>getopts</code> are:</p>
<ol>
<li>It's more portable, and will work in other shells like <code>dash</code>.</li>
<li>It can handle multiple single options like <code>-vf filename</code> in the typical Unix way, automatically.</li>
</ol>
<p>The disadvantage of <code>getopts</code> is that it can only handle short options (<code>-h</code>, not <code>--help</code>) without additional code.</p>
<p>There is a <a href="https://flokoe.github.io/bash-hackers-wiki/howto/getopts_tutorial" rel="noreferrer">getopts tutorial</a> which explains what all of the syntax and variables mean. In bash, there is also <code>help getopts</code>, which might be informative.</p>
|
<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4> <pre class="lang-bash prettyprint-override"><code>cat >/tmp/demo-space-separated.sh <<'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION="$2" shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH="$
|
387, 531, 1231, 2313, 19020
|
arguments, bash, command-line, getopts, scripting
|
<h1>How do I parse command line arguments in Bash?</h1>
<p>Say, I have a script that gets called with this line:</p>
<pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile
</code></pre>
<p>or this one:</p>
<pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile
</code></pre>
<p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 29
|
bash
|
# How do I parse command line arguments in Bash?
Say, I have a script that gets called with this line:
```
./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile
```
or this one:
```
./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile
```
What's the accepted way of parsing this such that in each case (or some combination of the two) `$v`, `$f`, and `$d` will all be set to `true` and `$outFile` will be equal to `/fizz/someOtherFile`?
|
#### Bash Space-Separated (e.g., `--option argument`)
```
cat >/tmp/demo-space-separated.sh <<'EOF'
#!/bin/bash
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-e|--extension)
EXTENSION="$2"
shift # past argument
shift # past value
;;
-s|--searchpath)
SEARCHPATH="$2"
shift # past argument
shift # past value
;;
--default)
DEFAULT=YES
shift # past argument
;;
-*|--*)
echo "Unknown option $1"
exit 1
;;
*)
POSITIONAL_ARGS+=("$1") # save positional arg
shift # past argument
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 "$1"
fi
EOF
chmod +x /tmp/demo-space-separated.sh
/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts
```
##### Output from copy-pasting the block above
```
FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
```
##### Usage
```
demo-space-separated.sh -e conf -s /etc /etc/hosts
```
---
#### Bash Equals-Separated (e.g., `--option=argument`)
```
cat >/tmp/demo-equals-separated.sh <<'EOF'
#!/bin/bash
for i in "$@"; do
case $i in
-e=*|--extension=*)
EXTENSION="${i#*=}"
shift # past argument=value
;;
-s=*|--searchpath=*)
SEARCHPATH="${i#*=}"
shift # past argument=value
;;
--default)
DEFAULT=YES
shift # past argument with no value
;;
-*|--*)
echo "Unknown option $i"
exit 1
;;
*)
;;
esac
done
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 $1
fi
EOF
chmod +x /tmp/demo-equals-separated.sh
/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
```
##### Output from copy-pasting the block above
```
FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
```
##### Usage
```
demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
```
---
To better understand `${i#*=}` search for "Substring Removal" in [this guide](http://tldp.org/LDP/abs/html/string-manipulation.html). It is functionally equivalent to `` `sed 's/[^=]*=//' <<< "$i"` `` which calls a needless subprocess or `` `echo "$i" | sed 's/[^=]*=//'` `` which calls *two* needless subprocesses.
---
#### Using bash with getopt[s]
getopt(1) limitations (older, relatively-recent `getopt` versions):
- can't handle arguments that are empty strings
- can't handle arguments with embedded whitespace
More recent `getopt` versions don't have these limitations. For more information, see these [docs](https://mywiki.wooledge.org/BashFAQ/035#getopts).
---
#### POSIX getopts
Additionally, the POSIX shell and others offer `getopts` which doen't have these limitations. I've included a simplistic `getopts` example.
```
cat >/tmp/demo-getopts.sh <<'EOF'
#!/bin/sh
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize our own variables:
output_file=""
verbose=0
while getopts "h?vf:" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v) verbose=1
;;
f) output_file=$OPTARG
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
echo "verbose=$verbose, output_file='$output_file', Leftovers: $@"
EOF
chmod +x /tmp/demo-getopts.sh
/tmp/demo-getopts.sh -vf /etc/hosts foo bar
```
##### Output from copy-pasting the block above
```
verbose=1, output_file='/etc/hosts', Leftovers: foo bar
```
##### Usage
```
demo-getopts.sh -vf /etc/hosts foo bar
```
The advantages of `getopts` are:
1. It's more portable, and will work in other shells like `dash`.
2. It can handle multiple single options like `-vf filename` in the typical Unix way, automatically.
The disadvantage of `getopts` is that it can only handle short options (`-h`, not `--help`) without additional code.
There is a [getopts tutorial](https://flokoe.github.io/bash-hackers-wiki/howto/getopts_tutorial) which explains what all of the syntax and variables mean. In bash, there is also `help getopts`, which might be informative.
|
818255
|
What does " 2>&1 " mean?
| 3,260
|
2009-05-03 22:57:00
|
<p>To combine <code>stderr</code> and <code>stdout</code> into the <code>stdout</code> stream, we append this to a command:</p>
<pre><code>2>&1
</code></pre>
<p>For example, the following command shows the first few errors from compiling <code>main.cpp</code>:</p>
<pre><code>g++ main.cpp 2>&1 | head
</code></pre>
<p>But what does <code>2>&1</code> mean?</p>
| 1,963,820
| 30,529
|
2024-11-07 14:50:17
| 818,284
| 3,676
|
2009-05-03 23:04:53
| 40,005
|
2022-07-17 06:18:24
|
https://stackoverflow.com/q/818255
|
https://stackoverflow.com/a/818284
|
<p>File descriptor 1 is the standard output (<code>stdout</code>).<br>
File descriptor 2 is the standard error (<code>stderr</code>).</p>
<p>At first, <code>2>1</code> may look like a good way to redirect <code>stderr</code> to <code>stdout</code>. However, it will actually be interpreted as "redirect <code>stderr</code> to a file named <code>1</code>".</p>
<p><code>&</code> indicates that what follows and precedes is a <em>file descriptor</em>, and not a filename. Thus, we use <code>2>&1</code>. Consider <code>>&</code> to be a redirect merger operator.</p>
|
<p>File descriptor 1 is the standard output (<code>stdout</code>).<br> File descriptor 2 is the standard error (<code>stderr</code>).</p> <p>At first, <code>2>1</code> may look like a good way to redirect <code>stderr</code> to <code>stdout</code>. However, it will actually be interpreted as "redirect <code>stderr</code> to a file named <code>1</code>".</p> <p><code>&</code> indic
|
34, 387, 390
|
bash, shell, unix
|
<h1>What does " 2>&1 " mean?</h1>
<p>To combine <code>stderr</code> and <code>stdout</code> into the <code>stdout</code> stream, we append this to a command:</p>
<pre><code>2>&1
</code></pre>
<p>For example, the following command shows the first few errors from compiling <code>main.cpp</code>:</p>
<pre><code>g++ main.cpp 2>&1 | head
</code></pre>
<p>But what does <code>2>&1</code> mean?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 30
|
bash
|
# What does " 2>&1 " mean?
To combine `stderr` and `stdout` into the `stdout` stream, we append this to a command:
```
2>&1
```
For example, the following command shows the first few errors from compiling `main.cpp`:
```
g++ main.cpp 2>&1 | head
```
But what does `2>&1` mean?
|
File descriptor 1 is the standard output (`stdout`).
File descriptor 2 is the standard error (`stderr`).
At first, `2>1` may look like a good way to redirect `stderr` to `stdout`. However, it will actually be interpreted as "redirect `stderr` to a file named `1`".
`&` indicates that what follows and precedes is a *file descriptor*, and not a filename. Thus, we use `2>&1`. Consider `>&` to be a redirect merger operator.
|
4037939
|
PowerShell says "execution of scripts is disabled on this system."
| 3,013
|
2010-10-27 21:39:29
|
<p>I am trying to run a <code>cmd</code> file that calls a PowerShell script from <code>cmd.exe</code>, but I am getting this error:</p>
<blockquote>
<p><code>Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system.</p>
</blockquote>
<p>I ran this command:</p>
<pre class="lang-none prettyprint-override"><code>Set-ExecutionPolicy -ExecutionPolicy Unrestricted
</code></pre>
<p>When I run <code>Get-ExecutionPolicy</code> from PowerShell, it returns <code>Unrestricted</code>.</p>
<pre class="lang-none prettyprint-override"><code>Get-ExecutionPolicy
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Unrestricted
</code></pre>
<hr />
<blockquote>
<p>cd "C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts"
powershell .\Management_Install.ps1 1</p>
<p>WARNING: Running x86 PowerShell...</p>
<p>File <code>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system. Please see "<code>get-help about_signing</code>" for more details.</p>
<p>At line:1 char:25</p>
<ul>
<li><p><code>.\Management_Install.ps1</code> <<<< 1</p>
<ul>
<li><p>CategoryInfo : NotSpecified: (:) [], PSSecurityException</p>
</li>
<li><p>FullyQualifiedErrorId : RuntimeException</p>
</li>
</ul>
</li>
</ul>
<p>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts> PAUSE</p>
<p>Press any key to continue . . .</p>
</blockquote>
<hr />
<p>The system is <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2.</p>
<p>What am I doing wrong?</p>
| 5,280,444
| 489,400
|
2025-08-24 19:14:52
| 4,038,991
| 3,670
|
2010-10-28 01:16:25
| 135,965
|
2022-02-24 18:26:00
|
https://stackoverflow.com/q/4037939
|
https://stackoverflow.com/a/4038991
|
<p>If you're using <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 then there is an <em>x64</em> and <em>x86</em> version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?</p>
<p>As an <em>Administrator</em>, you can set the execution policy by typing this into your PowerShell window:</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned
</code></pre>
<p>For more information, see <em><a href="https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy" rel="noreferrer">Using the Set-ExecutionPolicy Cmdlet</a></em>.</p>
<p>When you are done, you can set the policy back to its default value with:</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy Restricted
</code></pre>
<p>You may see an error:</p>
<pre class="lang-None prettyprint-override"><code>Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
To change the execution policy for the default (LocalMachine) scope,
start Windows PowerShell with the "Run as administrator" option.
To change the execution policy for the current user,
run "Set-ExecutionPolicy -Scope CurrentUser".
</code></pre>
<p>So you may need to run the command like this (as seen in comments):</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
</code></pre>
|
<p>If you're using <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 then there is an <em>x64</em> and <em>x86</em> version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?</p> <p>As an <em>Administrator</em>, you can set the execution policy by typing this into your PowerShe
|
526, 36466
|
powershell, windows-server-2008-r2
|
<h1>PowerShell says "execution of scripts is disabled on this system."</h1>
<p>I am trying to run a <code>cmd</code> file that calls a PowerShell script from <code>cmd.exe</code>, but I am getting this error:</p>
<blockquote>
<p><code>Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system.</p>
</blockquote>
<p>I ran this command:</p>
<pre class="lang-none prettyprint-override"><code>Set-ExecutionPolicy -ExecutionPolicy Unrestricted
</code></pre>
<p>When I run <code>Get-ExecutionPolicy</code> from PowerShell, it returns <code>Unrestricted</code>.</p>
<pre class="lang-none prettyprint-override"><code>Get-ExecutionPolicy
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Unrestricted
</code></pre>
<hr />
<blockquote>
<p>cd "C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts"
powershell .\Management_Install.ps1 1</p>
<p>WARNING: Running x86 PowerShell...</p>
<p>File <code>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system. Please see "<code>get-help about_signing</code>" for more details.</p>
<p>At line:1 char:25</p>
<ul>
<li><p><code>.\Management_Install.ps1</code> <<<< 1</p>
<ul>
<li><p>CategoryInfo : NotSpecified: (:) [], PSSecurityException</p>
</li>
<li><p>FullyQualifiedErrorId : RuntimeException</p>
</li>
</ul>
</li>
</ul>
<p>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts> PAUSE</p>
<p>Press any key to continue . . .</p>
</blockquote>
<hr />
<p>The system is <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2.</p>
<p>What am I doing wrong?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 31
|
bash
|
# PowerShell says "execution of scripts is disabled on this system."
I am trying to run a `cmd` file that calls a PowerShell script from `cmd.exe`, but I am getting this error:
> `Management_Install.ps1` cannot be loaded because the execution of scripts is disabled on this system.
I ran this command:
```
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
```
When I run `Get-ExecutionPolicy` from PowerShell, it returns `Unrestricted`.
```
Get-ExecutionPolicy
```
Output:
```
Unrestricted
```
---
> cd "C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts"
> powershell .\Management_Install.ps1 1
>
> WARNING: Running x86 PowerShell...
>
> File `C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1` cannot be loaded because the execution of scripts is disabled on this system. Please see "`get-help about_signing`" for more details.
>
> At line:1 char:25
>
> - `.\Management_Install.ps1` <<<< 1
>
> - CategoryInfo : NotSpecified: (:) [], PSSecurityException
> - FullyQualifiedErrorId : RuntimeException
>
> C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts> PAUSE
>
> Press any key to continue . . .
---
The system is [Windows Server 2008](https://en.wikipedia.org/wiki/Windows_Server_2008) R2.
What am I doing wrong?
|
If you're using [Windows Server 2008](https://en.wikipedia.org/wiki/Windows_Server_2008) R2 then there is an *x64* and *x86* version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?
As an *Administrator*, you can set the execution policy by typing this into your PowerShell window:
```
Set-ExecutionPolicy RemoteSigned
```
For more information, see *[Using the Set-ExecutionPolicy Cmdlet](https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy)*.
When you are done, you can set the policy back to its default value with:
```
Set-ExecutionPolicy Restricted
```
You may see an error:
```
Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
To change the execution policy for the default (LocalMachine) scope,
start Windows PowerShell with the "Run as administrator" option.
To change the execution policy for the current user,
run "Set-ExecutionPolicy -Scope CurrentUser".
```
So you may need to run the command like this (as seen in comments):
```
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
```
|
5410757
|
How can I delete all lines that contain a specific string from a text file?
| 2,416
|
2011-03-23 19:46:07
|
<p>How would I use sed to delete all lines in a text file that contain a specific string?</p>
| 2,684,037
| 667,236
|
2025-12-13 14:13:19
| 5,410,784
| 3,649
|
2011-03-23 19:48:46
| 207,248
|
2025-12-12 05:23:22
|
https://stackoverflow.com/q/5410757
|
https://stackoverflow.com/a/5410784
|
<p>To remove the line and print the output to standard out:</p>
<pre><code>sed '/pattern to match/d' ./infile
</code></pre>
<p>To directly modify the file (it does not work with BSD sed):</p>
<pre><code>sed -i '/pattern to match/d' ./infile
</code></pre>
<p>The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed):</p>
<pre><code>sed -i '' '/pattern to match/d' ./infile
</code></pre>
<p>To directly modify the file (and create a backup. It works with BSD and GNU sed):</p>
<pre><code>sed -i.bak '/pattern to match/d' ./infile
</code></pre>
|
<p>To remove the line and print the output to standard out:</p> <pre><code>sed '/pattern to match/d' ./infile </code></pre> <p>To directly modify the file (it does not work with BSD sed):</p> <pre><code>sed -i '/pattern to match/d' ./infile </code></pre> <p>The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed):</p> <pre><code>sed -i '' '/pattern to match/d' ./infile </cod
|
390, 5282, 12189, 13401
|
in-place, sed, shell, text-parsing
|
<h1>How can I delete all lines that contain a specific string from a text file?</h1>
<p>How would I use sed to delete all lines in a text file that contain a specific string?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 32
|
bash
|
# How can I delete all lines that contain a specific string from a text file?
How would I use sed to delete all lines in a text file that contain a specific string?
|
To remove the line and print the output to standard out:
```
sed '/pattern to match/d' ./infile
```
To directly modify the file (it does not work with BSD sed):
```
sed -i '/pattern to match/d' ./infile
```
The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed):
```
sed -i '' '/pattern to match/d' ./infile
```
To directly modify the file (and create a backup. It works with BSD and GNU sed):
```
sed -i.bak '/pattern to match/d' ./infile
```
|
8880603
|
Loop through an array of strings in Bash?
| 2,420
|
2012-01-16 13:21:16
|
<p>I want to write a script that loops through 15 strings (array possibly?) Is that possible?</p>
<pre><code>for databaseName in listOfNames
then
# Do something
end
</code></pre>
| 2,293,789
| 218,183
|
2025-11-19 13:31:32
| 8,880,633
| 3,621
|
2012-01-16 13:24:47
| 548,225
|
2025-11-19 13:31:32
|
https://stackoverflow.com/q/8880603
|
https://stackoverflow.com/a/8880633
|
<pre><code>## declare an array variable
declare -a arr=("element 1" "element 2" "element 3")
## loop through above array (quotes are important if your elements may contain spaces)
for i in "${arr[@]}"
do
echo "$i"
# or do whatever with individual element of array
done
# You can access them using echo "${arr[0]}", "${arr[1]}" also
</code></pre>
<p>Also works for multi-line array declaration</p>
<pre><code>declare -a arr=("element1"
"element2" "element3"
"element4"
)
</code></pre>
|
<pre><code>## declare an array variable declare -a arr=("element 1" "element 2" "element 3") ## loop through above array (quotes are important if your elements may contain spaces) for i in "${arr[@]}" do echo "$i" # or do whatever with individual element of array done # You can access them using echo "${arr[0]}", "${arr[1]}&q
|
114, 387, 390
|
arrays, bash, shell
|
<h1>Loop through an array of strings in Bash?</h1>
<p>I want to write a script that loops through 15 strings (array possibly?) Is that possible?</p>
<pre><code>for databaseName in listOfNames
then
# Do something
end
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 33
|
bash
|
# Loop through an array of strings in Bash?
I want to write a script that loops through 15 strings (array possibly?) Is that possible?
```
for databaseName in listOfNames
then
# Do something
end
```
|
```
## declare an array variable
declare -a arr=("element 1" "element 2" "element 3")
## loop through above array (quotes are important if your elements may contain spaces)
for i in "${arr[@]}"
do
echo "$i"
# or do whatever with individual element of array
done
# You can access them using echo "${arr[0]}", "${arr[1]}" also
```
Also works for multi-line array declaration
```
declare -a arr=("element1"
"element2" "element3"
"element4"
)
```
|
2518127
|
How to reload .bashrc settings without logging out and back in again?
| 2,268
|
2010-03-25 17:58:36
|
<p>If I make changes to <code>.bashrc</code>, how do I reload it without logging out and back in?</p>
| 1,888,242
| 292,553
|
2024-09-06 14:44:36
| 2,518,150
| 3,583
|
2010-03-25 18:01:04
| 245,602
|
2020-10-21 14:18:32
|
https://stackoverflow.com/q/2518127
|
https://stackoverflow.com/a/2518150
|
<p>You can enter the long form command:</p>
<pre><code>source ~/.bashrc
</code></pre>
<p>or you can use the shorter version of the command:</p>
<pre><code>. ~/.bashrc
</code></pre>
|
<p>You can enter the long form command:</p> <pre><code>source ~/.bashrc </code></pre> <p>or you can use the shorter version of the command:</p> <pre><code>. ~/.bashrc </code></pre>
|
387, 390, 391, 403, 12126
|
bash, profile, reload, shell, terminal
|
<h1>How to reload .bashrc settings without logging out and back in again?</h1>
<p>If I make changes to <code>.bashrc</code>, how do I reload it without logging out and back in?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 34
|
bash
|
# How to reload .bashrc settings without logging out and back in again?
If I make changes to `.bashrc`, how do I reload it without logging out and back in?
|
You can enter the long form command:
```
source ~/.bashrc
```
or you can use the shorter version of the command:
```
. ~/.bashrc
```
|
3601515
|
How to check if a variable is set in Bash
| 2,518
|
2010-08-30 14:54:38
|
<p>How do I know if a variable is set in Bash?</p>
<p>For example, how do I check if the user gave the first parameter to a function?</p>
<pre><code>function a {
# if $1 is set ?
}
</code></pre>
| 2,489,781
| 260,127
|
2024-01-11 07:53:29
| 13,864,829
| 3,468
|
2012-12-13 17:04:53
| 1,633,643
|
2021-12-06 18:12:01
|
https://stackoverflow.com/q/3601515
|
https://stackoverflow.com/a/13864829
|
<h2>(Usually) The right way</h2>
<pre><code>if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi
</code></pre>
<p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and substitutes the string <code>x</code> otherwise.</p>
<h3>Quotes Digression</h3>
<p>Quotes can be omitted (so we can say <code>${var+x}</code> instead of <code>"${var+x}"</code>) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to <code>x</code> (which contains no word breaks so it needs no quotes), or to nothing (which results in <code>[ -z ]</code>, which conveniently evaluates to the same value (true) that <code>[ -z "" ]</code> does as well)).</p>
<p>However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to <a href="https://stackoverflow.com/users/2255628/destiny-architect">the first author of this quotes explanation</a> who is also a major Bash coder), it would sometimes be better to write the solution with quotes as <code>[ -z "${var+x}" ]</code>, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.</p>
<h2>(Often) The wrong way</h2>
<pre><code>if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi
</code></pre>
<p>This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if <code>var=''</code>, then the above solution will output "var is blank".</p>
<p>The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.</p>
<p>The distinction may not be essential in every scenario though. In those cases <code>[ -z "$var" ]</code> will be just fine.</p>
|
<h2>(Usually) The right way</h2> <pre><code>if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi </code></pre> <p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and subst
|
276, 387, 390
|
bash, shell, variables
|
<h1>How to check if a variable is set in Bash</h1>
<p>How do I know if a variable is set in Bash?</p>
<p>For example, how do I check if the user gave the first parameter to a function?</p>
<pre><code>function a {
# if $1 is set ?
}
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 35
|
bash
|
# How to check if a variable is set in Bash
How do I know if a variable is set in Bash?
For example, how do I check if the user gave the first parameter to a function?
```
function a {
# if $1 is set ?
}
```
|
## (Usually) The right way
```
if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi
```
where `${var+x}` is a [parameter expansion](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02) which evaluates to nothing if `var` is unset, and substitutes the string `x` otherwise.
### Quotes Digression
Quotes can be omitted (so we can say `${var+x}` instead of `"${var+x}"`) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to `x` (which contains no word breaks so it needs no quotes), or to nothing (which results in `[ -z ]`, which conveniently evaluates to the same value (true) that `[ -z "" ]` does as well)).
However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to [the first author of this quotes explanation](https://stackoverflow.com/users/2255628/destiny-architect) who is also a major Bash coder), it would sometimes be better to write the solution with quotes as `[ -z "${var+x}" ]`, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.
## (Often) The wrong way
```
if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi
```
This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if `var=''`, then the above solution will output "var is blank".
The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
The distinction may not be essential in every scenario though. In those cases `[ -z "$var" ]` will be just fine.
|
6482377
|
Check existence of input argument in a Bash shell script
| 2,049
|
2011-06-26 05:49:21
|
<p>I need to check the existence of an input argument. I have the following script</p>
<pre><code>if [ "$1" -gt "-1" ]
then echo hi
fi
</code></pre>
<p>I get</p>
<pre><code>[: : integer expression expected
</code></pre>
<p>How do I check the input argument1 first to see if it exists?</p>
| 2,126,764
| 775,187
|
2024-06-03 04:03:01
| 6,482,403
| 3,395
|
2011-06-26 05:55:41
| 702,361
|
2021-01-28 08:38:46
|
https://stackoverflow.com/q/6482377
|
https://stackoverflow.com/a/6482403
|
<p>It is:</p>
<pre class="lang-bash prettyprint-override"><code>if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
</code></pre>
<p>The <code>$#</code> variable will tell you the number of input arguments the script was passed.</p>
<p>Or you can check if an argument is an empty string or not like:</p>
<pre><code>if [ -z "$1" ]
then
echo "No argument supplied"
fi
</code></pre>
<p>The <code>-z</code> switch will test if the expansion of <code>"$1"</code> is a null string or not. If it is a null string then the body is executed.</p>
|
<p>It is:</p> <pre class="lang-bash prettyprint-override"><code>if [ $# -eq 0 ] then echo "No arguments supplied" fi </code></pre> <p>The <code>$#</code> variable will tell you the number of input arguments the script was passed.</p> <p>Or you can check if an argument is an empty string or not like:</p> <pre><code>if [ -z "$1" ] then echo "No argument supplied&
|
387, 390
|
bash, shell
|
<h1>Check existence of input argument in a Bash shell script</h1>
<p>I need to check the existence of an input argument. I have the following script</p>
<pre><code>if [ "$1" -gt "-1" ]
then echo hi
fi
</code></pre>
<p>I get</p>
<pre><code>[: : integer expression expected
</code></pre>
<p>How do I check the input argument1 first to see if it exists?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 36
|
bash
|
# Check existence of input argument in a Bash shell script
I need to check the existence of an input argument. I have the following script
```
if [ "$1" -gt "-1" ]
then echo hi
fi
```
I get
```
[: : integer expression expected
```
How do I check the input argument1 first to see if it exists?
|
It is:
```
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
```
The `$#` variable will tell you the number of input arguments the script was passed.
Or you can check if an argument is an empty string or not like:
```
if [ -z "$1" ]
then
echo "No argument supplied"
fi
```
The `-z` switch will test if the expansion of `"$1"` is a null string or not. If it is a null string then the body is executed.
|
1358540
|
How can I count all the lines of code in a directory recursively?
| 2,114
|
2009-08-31 17:42:20
|
<p>We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.</p>
<p>We don't need to ignore comments, as we're just trying to get a rough idea.</p>
<pre><code>wc -l *.php
</code></pre>
<p>That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...</p>
<pre><code>find . -name '*.php' | wc -l
</code></pre>
<p>What's the correct syntax to feed in all the files from a directory resursively?</p>
| 1,285,868
| 77,413
|
2024-08-01 03:57:59
| 1,358,573
| 3,342
|
2009-08-31 17:50:12
| 76,794
|
2021-05-27 09:50:00
|
https://stackoverflow.com/q/1358540
|
https://stackoverflow.com/a/1358573
|
<p><strong>Try:</strong></p>
<pre><code>find . -name '*.php' | xargs wc -l
</code></pre>
<p>or (when file names include special characters such as spaces)</p>
<pre><code>find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l
</code></pre>
<p><strong><a href="https://dwheeler.com/sloccount/" rel="noreferrer">The SLOCCount tool</a></strong> may help as well.</p>
<p>It will give an accurate source lines of code count for whatever
hierarchy you point it at, as well as some additional stats.</p>
<p><strong>Sorted output:</strong></p>
<p><code>find . -name '*.php' | xargs wc -l | sort -nr</code></p>
|
<p><strong>Try:</strong></p> <pre><code>find . -name '*.php' | xargs wc -l </code></pre> <p>or (when file names include special characters such as spaces)</p> <pre><code>find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l </code></pre> <p><strong><a href="https://dwheeler.com/sloccount/" rel="noreferrer">The SLOCCount tool</a></strong> may help as well.</p> <p>It will give an accur
|
387, 390
|
bash, shell
|
<h1>How can I count all the lines of code in a directory recursively?</h1>
<p>We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.</p>
<p>We don't need to ignore comments, as we're just trying to get a rough idea.</p>
<pre><code>wc -l *.php
</code></pre>
<p>That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...</p>
<pre><code>find . -name '*.php' | wc -l
</code></pre>
<p>What's the correct syntax to feed in all the files from a directory resursively?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 37
|
bash
|
# How can I count all the lines of code in a directory recursively?
We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.
We don't need to ignore comments, as we're just trying to get a rough idea.
```
wc -l *.php
```
That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...
```
find . -name '*.php' | wc -l
```
What's the correct syntax to feed in all the files from a directory resursively?
|
**Try:**
```
find . -name '*.php' | xargs wc -l
```
or (when file names include special characters such as spaces)
```
find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l
```
**[The SLOCCount tool](https://dwheeler.com/sloccount/)** may help as well.
It will give an accurate source lines of code count for whatever
hierarchy you point it at, as well as some additional stats.
**Sorted output:**
`find . -name '*.php' | xargs wc -l | sort -nr`
|
4651437
|
How do I set a variable to the output of a command in Bash?
| 2,507
|
2011-01-10 20:58:02
|
<p>I have a pretty simple script that is something like the following:</p>
<pre><code>#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
</code></pre>
<p>When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the <code>$MOREF</code> variable, I am able to get output.</p>
<p>How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?</p>
| 3,105,029
| 570,402
|
2025-09-19 06:29:46
| 4,651,495
| 3,283
|
2011-01-10 21:04:18
| 8,454
|
2024-08-26 16:01:57
|
https://stackoverflow.com/q/4651437
|
https://stackoverflow.com/a/4651495
|
<p>In addition to backticks <code>`command`</code>, <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> can be done with <code>$(command)</code> or <code>"$(command)"</code>, which I find easier to read, and allows for nesting.</p>
<pre><code>OUTPUT="$(ls -1)"
echo "${OUTPUT}"
MULTILINE="$(ls \
-1)"
echo "${MULTILINE}"
</code></pre>
<p>Quoting (<code>"</code>) does matter to preserve <strong>multi-line variable values</strong> and it is safer to use with whitespace and special characters such as (<code>*</code>) and therefore advised; it is, however, optional on the right-hand side of an assignment when <a href="https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameters" rel="noreferrer">word splitting is not performed</a>, so <code>OUTPUT=$(ls -1)</code> would work fine.</p>
|
<p>In addition to backticks <code>`command`</code>, <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> can be done with <code>$(command)</code> or <code>"$(command)"</code>, which I find easier to read, and allows for nesting.</p> <pre><code>OUTPUT="$(ls -1)" echo "${OUTPUT}" MULTILINE="$
|
387, 390, 1231
|
bash, command-line, shell
|
<h1>How do I set a variable to the output of a command in Bash?</h1>
<p>I have a pretty simple script that is something like the following:</p>
<pre><code>#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
</code></pre>
<p>When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the <code>$MOREF</code> variable, I am able to get output.</p>
<p>How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 38
|
bash
|
# How do I set a variable to the output of a command in Bash?
I have a pretty simple script that is something like the following:
```
#!/bin/bash
VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'
echo $MOREF
```
When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the `$MOREF` variable, I am able to get output.
How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?
|
In addition to backticks `` `command` ``, [command substitution](http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution) can be done with `$(command)` or `"$(command)"`, which I find easier to read, and allows for nesting.
```
OUTPUT="$(ls -1)"
echo "${OUTPUT}"
MULTILINE="$(ls \
-1)"
echo "${MULTILINE}"
```
Quoting (`"`) does matter to preserve **multi-line variable values** and it is safer to use with whitespace and special characters such as (`*`) and therefore advised; it is, however, optional on the right-hand side of an assignment when [word splitting is not performed](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameters), so `OUTPUT=$(ls -1)` would work fine.
|
2264428
|
How to convert a string to lower case in Bash
| 1,893
|
2010-02-15 07:02:56
|
<p>Is there a way in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged 'bash'" rel="tag">bash</a> to convert a string into a lower case string?</p>
<p>For example, if I have:</p>
<pre><code>a="Hi all"
</code></pre>
<p>I want to convert it to:</p>
<pre><code>"hi all"
</code></pre>
| 1,602,361
| 266,008
|
2024-10-02 06:03:31
| 2,264,537
| 3,129
|
2010-02-15 07:43:20
| 131,527
|
2024-10-02 06:03:31
|
https://stackoverflow.com/q/2264428
|
https://stackoverflow.com/a/2264537
|
<p>There are various ways:</p>
<h3><a href="https://wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX standard</a></h3>
<h4><a href="https://wikipedia.org/wiki/Tr_%28Unix%29" rel="noreferrer">tr</a></h4>
<pre><code>$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
</code></pre>
<h4><a href="https://wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a></h4>
<pre><code>$ echo "$a" | awk '{print tolower($0)}'
hi all
</code></pre>
<h2>Non-POSIX</h2>
<p>You may run into portability issues with the following examples:</p>
<h4><a href="https://wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash 4.0</a></h4>
<pre><code>$ echo "${a,,}"
hi all
</code></pre>
<h4><a href="https://wikipedia.org/wiki/Sed" rel="noreferrer">sed</a></h4>
<pre><code>$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all
</code></pre>
<h4><a href="https://wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a></h4>
<pre><code>$ echo "$a" | perl -ne 'print lc'
hi all
</code></pre>
<h4><a href="https://wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a></h4>
<pre><code>lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done
</code></pre>
<p>Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but <code>nocasematch</code> is not implemented)) even with using <code>shopt -u nocasematch;</code>. Unsetting that <code>nocasematch</code> causes <code>[[ "fooBaR" == "FOObar" ]]</code> to match OK BUT inside case weirdly <code>[b-z]</code> are incorrectly matched by <code>[A-Z]</code>. Bash is confused by the double-negative ("unsetting nocasematch")! :-)</p>
|
<p>There are various ways:</p> <h3><a href="https://wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX standard</a></h3> <h4><a href="https://wikipedia.org/wiki/Tr_%28Unix%29" rel="noreferrer">tr</a></h4> <pre><code>$ echo "$a" | tr '[:upper:]' '[:lower:]' hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a></h4> <pre><code>$ echo "$a" | awk
|
139, 387, 390, 9848
|
bash, lowercase, shell, string
|
<h1>How to convert a string to lower case in Bash</h1>
<p>Is there a way in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged 'bash'" rel="tag">bash</a> to convert a string into a lower case string?</p>
<p>For example, if I have:</p>
<pre><code>a="Hi all"
</code></pre>
<p>I want to convert it to:</p>
<pre><code>"hi all"
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 39
|
bash
|
# How to convert a string to lower case in Bash
Is there a way in [bash](/questions/tagged/bash "show questions tagged 'bash'") to convert a string into a lower case string?
For example, if I have:
```
a="Hi all"
```
I want to convert it to:
```
"hi all"
```
|
There are various ways:
### [POSIX standard](https://wikipedia.org/wiki/POSIX)
#### [tr](https://wikipedia.org/wiki/Tr_%28Unix%29)
```
$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
```
#### [AWK](https://wikipedia.org/wiki/AWK)
```
$ echo "$a" | awk '{print tolower($0)}'
hi all
```
## Non-POSIX
You may run into portability issues with the following examples:
#### [Bash 4.0](https://wikipedia.org/wiki/Bash_%28Unix_shell%29)
```
$ echo "${a,,}"
hi all
```
#### [sed](https://wikipedia.org/wiki/Sed)
```
$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all
```
#### [Perl](https://wikipedia.org/wiki/Perl)
```
$ echo "$a" | perl -ne 'print lc'
hi all
```
#### [Bash](https://wikipedia.org/wiki/Bash_%28Unix_shell%29)
```
lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done
```
Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but `nocasematch` is not implemented)) even with using `shopt -u nocasematch;`. Unsetting that `nocasematch` causes `[[ "fooBaR" == "FOObar" ]]` to match OK BUT inside case weirdly `[b-z]` are incorrectly matched by `[A-Z]`. Bash is confused by the double-negative ("unsetting nocasematch")! :-)
|
1521462
|
Looping through the content of a file in Bash
| 2,202
|
2009-10-05 17:52:54
|
<p>How do I iterate through each line of a text file with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)" rel="noreferrer">Bash</a>?</p>
<p>With this script:</p>
<pre><code>echo "Start!"
for p in (peptides.txt)
do
echo "${p}"
done
</code></pre>
<p>I get this output on the screen:</p>
<pre><code>Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'
</code></pre>
<p>(Later I want to do something more complicated with <code>$p</code> than just output to the screen.)</p>
<hr>
<p>The environment variable <strong>SHELL</strong> is (from env):</p>
<pre><code>SHELL=/bin/bash
</code></pre>
<p><code>/bin/bash --version</code> output:</p>
<pre><code>GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
</code></pre>
<p><code>cat /proc/version</code> output:</p>
<pre><code>Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006
</code></pre>
<p>The file peptides.txt contains:</p>
<pre><code>RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
</code></pre>
| 3,042,183
| 63,550
|
2025-12-03 13:38:30
| 1,521,498
| 3,056
|
2009-10-05 18:00:20
| 6,918
|
2019-10-31 17:28:04
|
https://stackoverflow.com/q/1521462
|
https://stackoverflow.com/a/1521498
|
<p>One way to do it is:</p>
<pre><code>while read p; do
echo "$p"
done <peptides.txt
</code></pre>
<p>As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:</p>
<pre><code>while IFS="" read -r p || [ -n "$p" ]
do
printf '%s\n' "$p"
done < peptides.txt
</code></pre>
<hr>
<p>Exceptionally, if the <a href="https://unix.stackexchange.com/questions/107800/using-while-loop-to-ssh-to-multiple-servers">loop body may read from standard input</a>, you can open the file using a different file descriptor:</p>
<pre><code>while read -u 10 p; do
...
done 10<peptides.txt
</code></pre>
<p>Here, 10 is just an arbitrary number (different from 0, 1, 2).</p>
|
<p>One way to do it is:</p> <pre><code>while read p; do echo "$p" done <peptides.txt </code></pre> <p>As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:</p> <pre><code>while IFS="" read -r p || [ -n "$p" ] do printf
|
34, 58, 345, 387, 10327
|
bash, io, linux, sh, unix
|
<h1>Looping through the content of a file in Bash</h1>
<p>How do I iterate through each line of a text file with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)" rel="noreferrer">Bash</a>?</p>
<p>With this script:</p>
<pre><code>echo "Start!"
for p in (peptides.txt)
do
echo "${p}"
done
</code></pre>
<p>I get this output on the screen:</p>
<pre><code>Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'
</code></pre>
<p>(Later I want to do something more complicated with <code>$p</code> than just output to the screen.)</p>
<hr>
<p>The environment variable <strong>SHELL</strong> is (from env):</p>
<pre><code>SHELL=/bin/bash
</code></pre>
<p><code>/bin/bash --version</code> output:</p>
<pre><code>GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
</code></pre>
<p><code>cat /proc/version</code> output:</p>
<pre><code>Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006
</code></pre>
<p>The file peptides.txt contains:</p>
<pre><code>RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 40
|
bash
|
# Looping through the content of a file in Bash
How do I iterate through each line of a text file with [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell))?
With this script:
```
echo "Start!"
for p in (peptides.txt)
do
echo "${p}"
done
```
I get this output on the screen:
```
Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'
```
(Later I want to do something more complicated with `$p` than just output to the screen.)
---
The environment variable **SHELL** is (from env):
```
SHELL=/bin/bash
```
`/bin/bash --version` output:
```
GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
```
`cat /proc/version` output:
```
Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006
```
The file peptides.txt contains:
```
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
```
|
One way to do it is:
```
while read p; do
echo "$p"
done <peptides.txt
```
As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:
```
while IFS="" read -r p || [ -n "$p" ]
do
printf '%s\n' "$p"
done < peptides.txt
```
---
Exceptionally, if the [loop body may read from standard input](https://unix.stackexchange.com/questions/107800/using-while-loop-to-ssh-to-multiple-servers), you can open the file using a different file descriptor:
```
while read -u 10 p; do
...
done 10<peptides.txt
```
Here, 10 is just an arbitrary number (different from 0, 1, 2).
|
7131670
|
Make a Bash alias that takes a parameter?
| 1,899
|
2011-08-20 12:11:41
|
<p>I used to use CShell (<a href="/questions/tagged/csh" class="post-tag" title="show questions tagged 'csh'" rel="tag">csh</a>), which lets you make an alias that takes a parameter. The notation was something like</p>
<pre><code>alias junk="mv \\!* ~/.Trash"
</code></pre>
<p>In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.</p>
| 997,593
| 902,361
|
2025-02-04 10:19:27
| 7,131,683
| 2,996
|
2011-08-20 12:15:04
| 203,454
|
2019-04-11 08:24:04
|
https://stackoverflow.com/q/7131670
|
https://stackoverflow.com/a/7131683
|
<p>Bash alias does not directly accept parameters. You will have to create a function.</p>
<p><code>alias</code> does not accept parameters but a function can be called just like an alias. For example:</p>
<pre><code>myfunction() {
#do things with parameters like $1 such as
mv "$1" "$1.bak"
cp "$2" "$1"
}
myfunction old.conf new.conf #calls `myfunction`
</code></pre>
<p>By the way, Bash functions defined in your <code>.bashrc</code> and other files are available as commands within your shell. So for instance you can call the earlier function like this </p>
<pre><code>$ myfunction original.conf my.conf
</code></pre>
|
<p>Bash alias does not directly accept parameters. You will have to create a function.</p> <p><code>alias</code> does not accept parameters but a function can be called just like an alias. For example:</p> <pre><code>myfunction() { #do things with parameters like $1 such as mv "$1" "$1.bak" cp "$2" "$1" } myfunction old.conf new.conf #calls `myfunction` </code></pre> <p>By the way
|
387, 1448
|
alias, bash
|
<h1>Make a Bash alias that takes a parameter?</h1>
<p>I used to use CShell (<a href="/questions/tagged/csh" class="post-tag" title="show questions tagged 'csh'" rel="tag">csh</a>), which lets you make an alias that takes a parameter. The notation was something like</p>
<pre><code>alias junk="mv \\!* ~/.Trash"
</code></pre>
<p>In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 41
|
bash
|
# Make a Bash alias that takes a parameter?
I used to use CShell ([csh](/questions/tagged/csh "show questions tagged 'csh'")), which lets you make an alias that takes a parameter. The notation was something like
```
alias junk="mv \\!* ~/.Trash"
```
In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.
|
Bash alias does not directly accept parameters. You will have to create a function.
`alias` does not accept parameters but a function can be called just like an alias. For example:
```
myfunction() {
#do things with parameters like $1 such as
mv "$1" "$1.bak"
cp "$2" "$1"
}
myfunction old.conf new.conf #calls `myfunction`
```
By the way, Bash functions defined in your `.bashrc` and other files are available as commands within your shell. So for instance you can call the earlier function like this
```
$ myfunction original.conf my.conf
```
|
876239
|
How to redirect and append both standard output and standard error to a file with Bash
| 2,110
|
2009-05-18 04:19:45
|
<p>To redirect <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> to a truncated file in Bash, I know to use:</p>
<pre><code>cmd > file.txt
</code></pre>
<p>To redirect standard output in Bash, appending to a file, I know to use:</p>
<pre><code>cmd >> file.txt
</code></pre>
<p>To redirect both standard output and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a truncated file, I know to use:</p>
<pre><code>cmd &> file.txt
</code></pre>
<p>How do I redirect both standard output and standard error appending to a file? <code>cmd &>> file.txt</code> did not work for me.</p>
| 1,166,671
| 63,051
|
2023-11-19 09:42:16
| 876,242
| 2,670
|
2009-05-18 04:23:16
| 95,810
|
2017-03-09 14:55:58
|
https://stackoverflow.com/q/876239
|
https://stackoverflow.com/a/876242
|
<pre><code>cmd >>file.txt 2>&1
</code></pre>
<p>Bash executes the redirects from left to right as follows:</p>
<ol>
<li><code>>>file.txt</code>: Open <code>file.txt</code> in append mode and redirect <code>stdout</code> there.</li>
<li><code>2>&1</code>: Redirect <code>stderr</code> to <em>"where <code>stdout</code> is currently going"</em>. In this case, that is a file opened in append mode. In other words, the <code>&1</code> reuses the file descriptor which <code>stdout</code> currently uses.</li>
</ol>
|
<pre><code>cmd >>file.txt 2>&1 </code></pre> <p>Bash executes the redirects from left to right as follows:</p> <ol> <li><code>>>file.txt</code>: Open <code>file.txt</code> in append mode and redirect <code>stdout</code> there.</li> <li><code>2>&1</code>: Redirect <code>stderr</code> to <em>"where <code>stdout</code> is currently going"</em>. In this case, that is a file
|
387, 4867, 6051, 19156, 26698
|
append, bash, io-redirection, stderr, stdout
|
<h1>How to redirect and append both standard output and standard error to a file with Bash</h1>
<p>To redirect <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> to a truncated file in Bash, I know to use:</p>
<pre><code>cmd > file.txt
</code></pre>
<p>To redirect standard output in Bash, appending to a file, I know to use:</p>
<pre><code>cmd >> file.txt
</code></pre>
<p>To redirect both standard output and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a truncated file, I know to use:</p>
<pre><code>cmd &> file.txt
</code></pre>
<p>How do I redirect both standard output and standard error appending to a file? <code>cmd &>> file.txt</code> did not work for me.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 42
|
bash
|
# How to redirect and append both standard output and standard error to a file with Bash
To redirect [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) to a truncated file in Bash, I know to use:
```
cmd > file.txt
```
To redirect standard output in Bash, appending to a file, I know to use:
```
cmd >> file.txt
```
To redirect both standard output and [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) to a truncated file, I know to use:
```
cmd &> file.txt
```
How do I redirect both standard output and standard error appending to a file? `cmd &>> file.txt` did not work for me.
|
```
cmd >>file.txt 2>&1
```
Bash executes the redirects from left to right as follows:
1. `>>file.txt`: Open `file.txt` in append mode and redirect `stdout` there.
2. `2>&1`: Redirect `stderr` to *"where `stdout` is currently going"*. In this case, that is a file opened in append mode. In other words, the `&1` reuses the file descriptor which `stdout` currently uses.
|
2013547
|
Assigning default values to shell variables with a single command in bash
| 1,467
|
2010-01-06 14:29:31
|
<p>I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:</p>
<pre><code>if [ -z "${VARIABLE}" ]; then
FOO='default'
else
FOO=${VARIABLE}
fi
</code></pre>
<p>I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:</p>
<pre><code>FOO=${ ${VARIABLE} : 'default' }
</code></pre>
<p>(though I know that won't work...)</p>
<p>Am I crazy, or does something like that exist?</p>
| 984,074
| 87,408
|
2025-12-05 15:39:20
| 2,013,589
| 2,619
|
2010-01-06 14:36:56
| 241,774
|
2024-10-17 09:37:22
|
https://stackoverflow.com/q/2013547
|
https://stackoverflow.com/a/2013589
|
<p>Very close to what you posted, actually. You can use something called <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Bash parameter expansion</a> to accomplish this.</p>
<p>To get the assigned value, or <code>default</code> if it's missing:</p>
<pre><code>FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null.
# The value of VARIABLE remains untouched.
</code></pre>
<p>To do the same, as well as assign <code>default</code> to <code>VARIABLE</code>:</p>
<pre><code>FOO="${VARIABLE:=default}" # If VARIABLE not set or null, set its value to 'default'.
# Then that value will be assigned to FOO
</code></pre>
|
<p>Very close to what you posted, actually. You can use something called <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Bash parameter expansion</a> to accomplish this.</p> <p>To get the assigned value, or <code>default</code> if it's missing:</p> <pre><code>FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if
|
387, 390
|
bash, shell
|
<h1>Assigning default values to shell variables with a single command in bash</h1>
<p>I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:</p>
<pre><code>if [ -z "${VARIABLE}" ]; then
FOO='default'
else
FOO=${VARIABLE}
fi
</code></pre>
<p>I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:</p>
<pre><code>FOO=${ ${VARIABLE} : 'default' }
</code></pre>
<p>(though I know that won't work...)</p>
<p>Am I crazy, or does something like that exist?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 43
|
bash
|
# Assigning default values to shell variables with a single command in bash
I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:
```
if [ -z "${VARIABLE}" ]; then
FOO='default'
else
FOO=${VARIABLE}
fi
```
I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:
```
FOO=${ ${VARIABLE} : 'default' }
```
(though I know that won't work...)
Am I crazy, or does something like that exist?
|
Very close to what you posted, actually. You can use something called [Bash parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) to accomplish this.
To get the assigned value, or `default` if it's missing:
```
FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null.
# The value of VARIABLE remains untouched.
```
To do the same, as well as assign `default` to `VARIABLE`:
```
FOO="${VARIABLE:=default}" # If VARIABLE not set or null, set its value to 'default'.
# Then that value will be assigned to FOO
```
|
3137094
|
Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal
| 1,458
|
2010-06-29 00:31:31
|
<p>I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually...</p>
<pre><code>09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00
09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00
09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00
09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00
</code></pre>
<p>Is there a way to count in Linux Terminal?</p>
| 1,924,090
| 368,453
|
2024-09-13 12:33:01
| 3,137,099
| 2,601
|
2010-06-29 00:33:38
| 85,509
|
2015-04-29 19:27:45
|
https://stackoverflow.com/q/3137094
|
https://stackoverflow.com/a/3137099
|
<p>Use <code>wc</code>:</p>
<pre><code>wc -l <filename>
</code></pre>
<p>This will output the number of lines in <code><filename></code>:</p>
<pre><code>$ wc -l /dir/file.txt
3272485 /dir/file.txt
</code></pre>
<p>Or, to omit the <code><filename></code> from the result use <code>wc -l < <filename></code>:</p>
<pre><code>$ wc -l < /dir/file.txt
3272485
</code></pre>
<p>You can also pipe data to <code>wc</code> as well:</p>
<pre><code>$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63
</code></pre>
|
<p>Use <code>wc</code>:</p> <pre><code>wc -l <filename> </code></pre> <p>This will output the number of lines in <code><filename></code>:</p> <pre><code>$ wc -l /dir/file.txt 3272485 /dir/file.txt </code></pre> <p>Or, to omit the <code><filename></code> from the result use <code>wc -l < <filename></code>:</p> <pre><code>$ wc -l < /dir/file.txt 3272485 </code></pr
|
58, 387, 531, 1231
|
bash, command-line, linux, scripting
|
<h1>Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal</h1>
<p>I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually...</p>
<pre><code>09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00
09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00
09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00
09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00
</code></pre>
<p>Is there a way to count in Linux Terminal?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 44
|
bash
|
# Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal
I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually...
```
09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00
09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00
09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00
09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00
09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00
```
Is there a way to count in Linux Terminal?
|
Use `wc`:
```
wc -l <filename>
```
This will output the number of lines in `<filename>`:
```
$ wc -l /dir/file.txt
3272485 /dir/file.txt
```
Or, to omit the `<filename>` from the result use `wc -l < <filename>`:
```
$ wc -l < /dir/file.txt
3272485
```
You can also pipe data to `wc` as well:
```
$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63
```
|
169511
|
How do I iterate over a range of numbers defined by variables in Bash?
| 2,273
|
2008-10-04 01:38:43
|
<p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p>
<p>I know I can do this (called "sequence expression" in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p>
<pre><code>for i in {1..5}; do echo $i; done
</code></pre>
<p>Which gives:</p>
<blockquote>
<p>1 <br/>
2 <br/>
3 <br/>
4 <br/>
5</p>
</blockquote>
<p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p>
<pre><code>END=5
for i in {1..$END}; do echo $i; done
</code></pre>
<p>Which prints:</p>
<blockquote>
<p>{1..5}</p>
</blockquote>
| 1,926,914
| 24,923
|
2024-10-05 16:49:03
| 169,517
| 2,507
|
2008-10-04 01:41:55
| 2,908
|
2016-04-23 00:41:06
|
https://stackoverflow.com/q/169511
|
https://stackoverflow.com/a/169517
|
<pre><code>for i in $(seq 1 $END); do echo $i; done</code></pre>
<p>edit: I prefer <code>seq</code> over the other methods because I can actually remember it ;)</p>
|
<pre><code>for i in $(seq 1 $END); do echo $i; done</code></pre> <p>edit: I prefer <code>seq</code> over the other methods because I can actually remember it ;)</p>
|
367, 387, 390, 2531
|
bash, for-loop, shell, syntax
|
<h1>How do I iterate over a range of numbers defined by variables in Bash?</h1>
<p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p>
<p>I know I can do this (called "sequence expression" in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p>
<pre><code>for i in {1..5}; do echo $i; done
</code></pre>
<p>Which gives:</p>
<blockquote>
<p>1 <br/>
2 <br/>
3 <br/>
4 <br/>
5</p>
</blockquote>
<p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p>
<pre><code>END=5
for i in {1..$END}; do echo $i; done
</code></pre>
<p>Which prints:</p>
<blockquote>
<p>{1..5}</p>
</blockquote>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 45
|
bash
|
# How do I iterate over a range of numbers defined by variables in Bash?
How do I iterate over a range of numbers in Bash when the range is given by a variable?
I know I can do this (called "sequence expression" in the Bash [documentation](http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion)):
```
for i in {1..5}; do echo $i; done
```
Which gives:
> 1
> 2
> 3
> 4
> 5
Yet, how can I replace either of the range endpoints with a variable? This doesn't work:
```
END=5
for i in {1..$END}; do echo $i; done
```
Which prints:
> {1..5}
|
```
for i in $(seq 1 $END); do echo $i; done
```
edit: I prefer `seq` over the other methods because I can actually remember it ;)
|
1401482
|
YYYY-MM-DD format date in shell script
| 1,617
|
2009-09-09 19:06:56
|
<p>I tried using <code>$(date)</code> in my bash shell script, however, I want the date in <code>YYYY-MM-DD</code> format.<br>
How do I get this?</p>
| 2,304,731
| 45,730
|
2024-08-06 13:04:41
| 1,401,495
| 2,406
|
2009-09-09 19:08:57
| 11,123
|
2024-08-06 13:04:41
|
https://stackoverflow.com/q/1401482
|
https://stackoverflow.com/a/1401495
|
<p>In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external <code>date</code> (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow <code>fork()</code> call on Windows.</p>
<p>As such:</p>
<pre><code># put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
</code></pre>
<p>In bash (<4.2):</p>
<pre><code># put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
</code></pre>
<p>Other available date formats can be viewed from the <a href="http://man7.org/linux/man-pages/man1/date.1.html" rel="noreferrer">date man pages</a> (for external non-bash specific command):</p>
<pre><code>man date
</code></pre>
|
<p>In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external <code>date</code> (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow <code>fork()</code> call on Windows.</p> <p>As such:</p> <pre><code># put current date as yyyy-mm-dd in $date # -1 -> explicit current date, bash >=4.3 defaul
|
387, 390, 5002, 10823, 35771
|
bash, date, date-formatting, shell, strftime
|
<h1>YYYY-MM-DD format date in shell script</h1>
<p>I tried using <code>$(date)</code> in my bash shell script, however, I want the date in <code>YYYY-MM-DD</code> format.<br>
How do I get this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 46
|
bash
|
# YYYY-MM-DD format date in shell script
I tried using `$(date)` in my bash shell script, however, I want the date in `YYYY-MM-DD` format.
How do I get this?
|
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external `date` (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow `fork()` call on Windows.
As such:
```
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
```
In bash (<4.2):
```
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
```
Other available date formats can be viewed from the [date man pages](http://man7.org/linux/man-pages/man1/date.1.html) (for external non-bash specific command):
```
man date
```
|
6212219
|
Passing parameters to a Bash function
| 1,578
|
2011-06-02 08:35:17
|
<p>I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the <em>command line</em>.</p>
<p>I would like to pass parameters within my script. I tried:</p>
<pre><code>myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
</code></pre>
<p>But the syntax is not correct. How can I pass a parameter to my function?</p>
| 2,039,197
| 445,543
|
2024-11-20 15:20:36
| 6,212,408
| 2,399
|
2011-06-02 08:57:02
| 7,412
|
2020-12-18 16:27:37
|
https://stackoverflow.com/q/6212219
|
https://stackoverflow.com/a/6212408
|
<p>There are two typical ways of declaring a function. I prefer the second approach.</p>
<pre><code>function function_name {
command...
}
</code></pre>
<p>or</p>
<pre><code>function_name () {
command...
}
</code></pre>
<p>To call a function with arguments:</p>
<pre><code>function_name "$arg1" "$arg2"
</code></pre>
<p>The function refers to passed arguments by their position (not by name), that is <code>$1</code>, <code>$2</code>, and so forth. <strong><code>$0</code></strong> is the name of the script itself.</p>
<p>Example:</p>
<pre><code>function_name () {
echo "Parameter #1 is $1"
}
</code></pre>
<p>Also, you need to call your function <strong>after</strong> it is declared.</p>
<pre><code>#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
</code></pre>
<p><strong>Output:</strong></p>
<pre class="lang-none prettyprint-override"><code>./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
</code></pre>
<p><a href="http://tldp.org/LDP/abs/html/complexfunct.html" rel="noreferrer">Reference: Advanced Bash-Scripting Guide</a>.</p>
|
<p>There are two typical ways of declaring a function. I prefer the second approach.</p> <pre><code>function function_name { command... } </code></pre> <p>or</p> <pre><code>function_name () { command... } </code></pre> <p>To call a function with arguments:</p> <pre><code>function_name "$arg1" "$arg2" </code></pre> <p>The function refers to passed arguments by their posi
|
360, 387, 2313, 5569
|
arguments, bash, function, parameters
|
<h1>Passing parameters to a Bash function</h1>
<p>I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the <em>command line</em>.</p>
<p>I would like to pass parameters within my script. I tried:</p>
<pre><code>myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
</code></pre>
<p>But the syntax is not correct. How can I pass a parameter to my function?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 47
|
bash
|
# Passing parameters to a Bash function
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the *command line*.
I would like to pass parameters within my script. I tried:
```
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
```
But the syntax is not correct. How can I pass a parameter to my function?
|
There are two typical ways of declaring a function. I prefer the second approach.
```
function function_name {
command...
}
```
or
```
function_name () {
command...
}
```
To call a function with arguments:
```
function_name "$arg1" "$arg2"
```
The function refers to passed arguments by their position (not by name), that is `$1`, `$2`, and so forth. **`$0`** is the name of the script itself.
Example:
```
function_name () {
echo "Parameter #1 is $1"
}
```
Also, you need to call your function **after** it is declared.
```
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
```
**Output:**
```
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
```
[Reference: Advanced Bash-Scripting Guide](http://tldp.org/LDP/abs/html/complexfunct.html).
|
13210880
|
Replace one substring for another string in shell script
| 1,457
|
2012-11-03 16:01:23
|
<p>I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".</p>
<pre><code>firstString="I love Suzi and Marry"
secondString="Sara"
</code></pre>
<p>Desired result:</p>
<pre><code>firstString="I love Sara and Marry"
</code></pre>
| 1,824,557
| 1,796,726
|
2024-06-17 13:39:36
| 13,210,909
| 2,391
|
2012-11-03 16:05:06
| 978,917
|
2024-06-17 13:39:36
|
https://stackoverflow.com/q/13210880
|
https://stackoverflow.com/a/13210909
|
<p>To replace the <em>first</em> occurrence of a pattern with a given string, use <code>${<em>parameter</em>/<em>pattern</em>/<em>string</em>}</code>:</p>
<pre><code>#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/"$secondString"}"
# prints 'I love Sara and Marry'
</code></pre>
<p>To replace <em>all</em> occurrences, use <code>${<em>parameter</em>//<em>pattern</em>/<em>string</em>}</code>:</p>
<pre><code>message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
</code></pre>
<p>(This is documented in <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion" rel="noreferrer">the <em>Bash Reference Manual</em>, §3.5.3 "Shell Parameter Expansion"</a>.)</p>
<p>Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer"><em>The Open Group Technical Standard Base Specifications, Issue 7</em>, the <em>Shell & Utilities</em> volume, §2.6.2 "Parameter Expansion"</a>.</p>
|
<p>To replace the <em>first</em> occurrence of a pattern with a given string, use <code>${<em>parameter</em>/<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>#!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" echo "${firstString/Suzi/"$secondString"}" # prints 'I love Sara and Marry' </code></pre> <p>To replace <em>all</em> occurrenc
|
387, 390
|
bash, shell
|
<h1>Replace one substring for another string in shell script</h1>
<p>I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".</p>
<pre><code>firstString="I love Suzi and Marry"
secondString="Sara"
</code></pre>
<p>Desired result:</p>
<pre><code>firstString="I love Sara and Marry"
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 48
|
bash
|
# Replace one substring for another string in shell script
I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".
```
firstString="I love Suzi and Marry"
secondString="Sara"
```
Desired result:
```
firstString="I love Sara and Marry"
```
|
To replace the *first* occurrence of a pattern with a given string, use `${parameter/pattern/string}`:
```
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/"$secondString"}"
# prints 'I love Sara and Marry'
```
To replace *all* occurrences, use `${parameter//pattern/string}`:
```
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
```
(This is documented in [the *Bash Reference Manual*, §3.5.3 "Shell Parameter Expansion"](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion).)
Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see [*The Open Group Technical Standard Base Specifications, Issue 7*, the *Shell & Utilities* volume, §2.6.2 "Parameter Expansion"](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02).
|
418896
|
How to redirect output to a file and stdout
| 1,677
|
2009-01-07 01:45:42
|
<p>In bash, calling <code>foo</code> would display any output from that command on the stdout.</p>
<p>Calling <code>foo > output</code> would redirect any output from that command to the file specified (in this case 'output').</p>
<p>Is there a way to redirect output to a file <em>and</em> have it display on stdout?</p>
| 1,246,622
| 1,666
|
2024-03-19 09:17:37
| 418,899
| 2,378
|
2009-01-07 01:48:08
| 20,267
|
2017-10-23 17:10:56
|
https://stackoverflow.com/q/418896
|
https://stackoverflow.com/a/418899
|
<p>The command you want is named <strong><a href="http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer"><code>tee</code></a></strong>:</p>
<pre><code>foo | tee output.file
</code></pre>
<p>For example, if you only care about stdout:</p>
<pre><code>ls -a | tee output.file
</code></pre>
<p>If you want to include stderr, do:</p>
<pre><code>program [arguments...] 2>&1 | tee outfile
</code></pre>
<p><code>2>&1</code> redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the <code>tee</code> command.</p>
<p>Furthermore, if you want to <em>append</em> to the log file, use <code>tee -a</code> as:</p>
<pre><code>program [arguments...] 2>&1 | tee -a outfile
</code></pre>
|
<p>The command you want is named <strong><a href="http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer"><code>tee</code></a></strong>:</p> <pre><code>foo | tee output.file </code></pre> <p>For example, if you only care about stdout:</p> <pre><code>ls -a | tee output.file </code></pre> <p>If you want to include stderr, do:</p> <pre><code>program [argument
|
58, 345, 387, 724, 4867
|
bash, file-io, io, linux, stdout
|
<h1>How to redirect output to a file and stdout</h1>
<p>In bash, calling <code>foo</code> would display any output from that command on the stdout.</p>
<p>Calling <code>foo > output</code> would redirect any output from that command to the file specified (in this case 'output').</p>
<p>Is there a way to redirect output to a file <em>and</em> have it display on stdout?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 49
|
bash
|
# How to redirect output to a file and stdout
In bash, calling `foo` would display any output from that command on the stdout.
Calling `foo > output` would redirect any output from that command to the file specified (in this case 'output').
Is there a way to redirect output to a file *and* have it display on stdout?
|
The command you want is named **[`tee`](http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html)**:
```
foo | tee output.file
```
For example, if you only care about stdout:
```
ls -a | tee output.file
```
If you want to include stderr, do:
```
program [arguments...] 2>&1 | tee outfile
```
`2>&1` redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the `tee` command.
Furthermore, if you want to *append* to the log file, use `tee -a` as:
```
program [arguments...] 2>&1 | tee -a outfile
```
|
4608187
|
How to reload .bash_profile from the command line
| 1,234
|
2011-01-05 19:09:07
|
<p>How can I reload file <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example" rel="noreferrer">.bash_profile</a> from the <em>command line</em>?</p>
<p>I can get the shell to recognize changes to <em>.bash_profile</em> by exiting and logging back in, but I would like to be able to do it on demand.</p>
| 1,217,536
| 97,101
|
2024-10-08 02:19:42
| 4,608,197
| 2,292
|
2011-01-05 19:10:03
| 207,248
|
2024-10-08 02:19:42
|
https://stackoverflow.com/q/4608187
|
https://stackoverflow.com/a/4608197
|
<p>Simply type <code>source ~/.bash_profile</code></p>
<p>Alternatively, if you like saving keystrokes, you can type <code>. ~/.bash_profile</code></p>
|
<p>Simply type <code>source ~/.bash_profile</code></p> <p>Alternatively, if you like saving keystrokes, you can type <code>. ~/.bash_profile</code></p>
|
387, 390, 1231
|
bash, command-line, shell
|
<h1>How to reload .bash_profile from the command line</h1>
<p>How can I reload file <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example" rel="noreferrer">.bash_profile</a> from the <em>command line</em>?</p>
<p>I can get the shell to recognize changes to <em>.bash_profile</em> by exiting and logging back in, but I would like to be able to do it on demand.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 50
|
bash
|
# How to reload .bash_profile from the command line
How can I reload file [.bash_profile](https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example) from the *command line*?
I can get the shell to recognize changes to *.bash_profile* by exiting and logging back in, but I would like to be able to do it on demand.
|
Simply type `source ~/.bash_profile`
Alternatively, if you like saving keystrokes, you can type `. ~/.bash_profile`
|
343646
|
Ignoring directories in Git repositories on Windows
| 1,592
|
2008-12-05 12:17:28
|
<p>How can I ignore directories or folders in Git using msysgit on Windows?</p>
| 2,050,509
| 43,603
|
2025-05-29 14:10:31
| 343,734
| 2,241
|
2008-12-05 12:54:10
| 43,613
|
2019-11-14 13:48:32
|
https://stackoverflow.com/q/343646
|
https://stackoverflow.com/a/343734
|
<p>Create a file named <code>.gitignore</code> in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):</p>
<pre><code>dir_to_ignore/
</code></pre>
<p>More information is <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">here</a>.</p>
|
<p>Create a file named <code>.gitignore</code> in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):</p> <pre><code>dir_to_ignore/ </code></pre> <p>More information is <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">here</a>.</p>
|
64, 119, 21628, 25056, 61874
|
git, git-bash, gitignore, msysgit, windows
|
<h1>Ignoring directories in Git repositories on Windows</h1>
<p>How can I ignore directories or folders in Git using msysgit on Windows?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 51
|
bash
|
# Ignoring directories in Git repositories on Windows
How can I ignore directories or folders in Git using msysgit on Windows?
|
Create a file named `.gitignore` in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):
```
dir_to_ignore/
```
More information is [here](http://git-scm.com/docs/gitignore).
|
2990414
|
echo that outputs to stderr
| 1,686
|
2010-06-07 14:36:16
|
<p>Is there a standard Bash command that acts like <code>echo</code> but outputs to stderr rather than stdout?</p>
<p>I know I can do <code>echo foo 1>&2</code> but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).</p>
| 1,048,664
| 1,343
|
2023-10-10 06:11:19
| 23,550,347
| 2,201
|
2014-05-08 18:59:47
| 675,584
|
2023-05-09 22:29:35
|
https://stackoverflow.com/q/2990414
|
https://stackoverflow.com/a/23550347
|
<p>You could do this, which facilitates reading:</p>
<pre><code>>&2 echo "error"
</code></pre>
<p><code>>&2</code> copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was <strong>originally</strong> referring to. For more information see the <a href="https://web.archive.org/web/20230315225157/https://wiki.bash-hackers.org/howto/redirection_tutorial" rel="noreferrer">Bash Hackers Illustrated Redirection Tutorial</a>.</p>
|
<p>You could do this, which facilitates reading:</p> <pre><code>>&2 echo "error" </code></pre> <p><code>>&2</code> copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was <strong>originally</strong> referring to. For more information see the <a href="ht
|
387
|
bash
|
<h1>echo that outputs to stderr</h1>
<p>Is there a standard Bash command that acts like <code>echo</code> but outputs to stderr rather than stdout?</p>
<p>I know I can do <code>echo foo 1>&2</code> but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 52
|
bash
|
# echo that outputs to stderr
Is there a standard Bash command that acts like `echo` but outputs to stderr rather than stdout?
I know I can do `echo foo 1>&2` but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).
|
You could do this, which facilitates reading:
```
>&2 echo "error"
```
`>&2` copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was **originally** referring to. For more information see the [Bash Hackers Illustrated Redirection Tutorial](https://web.archive.org/web/20230315225157/https://wiki.bash-hackers.org/howto/redirection_tutorial).
|
226703
|
How do I prompt for Yes/No/Cancel input in a Linux shell script?
| 1,921
|
2008-10-22 17:03:22
|
<p>I want to pause input in a shell script, and prompt the user for choices.<br>
The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br>
How do I accomplish this in a typical bash prompt?</p>
| 1,415,315
| 9,084
|
2026-01-06 20:54:44
| 226,724
| 2,092
|
2008-10-22 17:08:50
| 9,084
|
2025-03-18 14:21:37
|
https://stackoverflow.com/q/226703
|
https://stackoverflow.com/a/226724
|
<p>A widely available method to get user input at a shell prompt is the <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-read" rel="noreferrer"><code>read</code></a> command. Here is a demonstration:</p>
<pre><code>while true; do
read -p "Do you wish to install this program? " yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
</code></pre>
<hr />
<p>Another method, <a href="https://stackoverflow.com/a/226946/9084">pointed out</a> by <a href="https://stackoverflow.com/users/28604/steven-huwig">Steven Huwig</a>, is Bash's <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-select" rel="noreferrer"><code>select</code></a> command. Here is the same example using <code>select</code>:</p>
<pre><code>echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
</code></pre>
<p>With <code>select</code> you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a <code>while true</code> loop to retry if they give invalid input. If you want to allow more flexible input (accepting the words of the options, rather than <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-select" rel="noreferrer">just their number</a>), you can alter it like this:</p>
<pre><code>echo "Do you wish to install this program?"
select strictreply in "Yes" "No"; do
relaxedreply=${strictreply:-$REPLY}
case $relaxedreply in
Yes | yes | y ) make install; break;;
No | no | n ) exit;;
esac
done
</code></pre>
<hr />
<p>Also, <a href="https://stackoverflow.com/users/7939871/l%c3%a9a-gris">Léa Gris</a> demonstrated a way to make the request language agnostic in <a href="https://stackoverflow.com/a/57739142/9084">her answer</a>. Adapting my first example to better serve multiple languages might look like this:</p>
<pre><code>set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
if [[ "$yn" =~ $noexpr ]]; then exit; fi
echo "Answer ${yesword} / ${noword}."
done
</code></pre>
<p>Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.</p>
<hr />
<p>Finally, please check out the <a href="https://stackoverflow.com/a/27875395/9084">excellent answer</a> by <a href="https://stackoverflow.com/users/1765658/f-hauri">F. Hauri</a>.</p>
|
<p>A widely available method to get user input at a shell prompt is the <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-read" rel="noreferrer"><code>read</code></a> command. Here is a demonstration:</p> <pre><code>while true; do read -p "Do you wish to install this program? " yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;;
|
58, 387, 390, 531
|
bash, linux, scripting, shell
|
<h1>How do I prompt for Yes/No/Cancel input in a Linux shell script?</h1>
<p>I want to pause input in a shell script, and prompt the user for choices.<br>
The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br>
How do I accomplish this in a typical bash prompt?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 53
|
bash
|
# How do I prompt for Yes/No/Cancel input in a Linux shell script?
I want to pause input in a shell script, and prompt the user for choices.
The standard `Yes`, `No`, or `Cancel` type question.
How do I accomplish this in a typical bash prompt?
|
A widely available method to get user input at a shell prompt is the [`read`](https://www.gnu.org/software/bash/manual/bashref.html#index-read) command. Here is a demonstration:
```
while true; do
read -p "Do you wish to install this program? " yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
```
---
Another method, [pointed out](https://stackoverflow.com/a/226946/9084) by [Steven Huwig](https://stackoverflow.com/users/28604/steven-huwig), is Bash's [`select`](https://www.gnu.org/software/bash/manual/bashref.html#index-select) command. Here is the same example using `select`:
```
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
```
With `select` you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a `while true` loop to retry if they give invalid input. If you want to allow more flexible input (accepting the words of the options, rather than [just their number](https://www.gnu.org/software/bash/manual/bashref.html#index-select)), you can alter it like this:
```
echo "Do you wish to install this program?"
select strictreply in "Yes" "No"; do
relaxedreply=${strictreply:-$REPLY}
case $relaxedreply in
Yes | yes | y ) make install; break;;
No | no | n ) exit;;
esac
done
```
---
Also, [Léa Gris](https://stackoverflow.com/users/7939871/l%c3%a9a-gris) demonstrated a way to make the request language agnostic in [her answer](https://stackoverflow.com/a/57739142/9084). Adapting my first example to better serve multiple languages might look like this:
```
set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
if [[ "$yn" =~ $noexpr ]]; then exit; fi
echo "Answer ${yesword} / ${noword}."
done
```
Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.
---
Finally, please check out the [excellent answer](https://stackoverflow.com/a/27875395/9084) by [F. Hauri](https://stackoverflow.com/users/1765658/f-hauri).
|
4824590
|
Propagate all arguments in a Bash shell script
| 1,291
|
2011-01-28 03:34:04
|
<p>I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.</p>
<p>For instance, my script name is <code>foo.sh</code> and calls <code>bar.sh</code>.</p>
<p>foo.sh:</p>
<pre><code>bar $1 $2 $3 $4
</code></pre>
<p>How can I do this without explicitly specifying each parameter?</p>
| 737,326
| 121,112
|
2026-01-14 22:40:28
| 4,824,637
| 2,024
|
2011-01-28 03:42:43
| 401,390
|
2026-01-14 22:40:28
|
https://stackoverflow.com/q/4824590
|
https://stackoverflow.com/a/4824637
|
<p>Use <code>"$@"</code> instead of plain <code>$@</code> if you actually wish your parameters to be passed exactly as is.</p>
<p>Observe:</p>
<pre class="lang-bash prettyprint-override"><code>$ cat no_quotes.sh
#!/bin/bash
./echo_args.sh $@
$ cat quotes.sh
#!/bin/bash
./echo_args.sh "$@"
$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4
$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:
$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:
</code></pre>
|
<p>Use <code>"$@"</code> instead of plain <code>$@</code> if you actually wish your parameters to be passed exactly as is.</p> <p>Observe:</p> <pre class="lang-bash prettyprint-override"><code>$ cat no_quotes.sh #!/bin/bash ./echo_args.sh $@ $ cat quotes.sh #!/bin/bash ./echo_args.sh "$@" $ cat echo_args.sh #!/bin/bash echo Received: $1 echo Received: $2 echo Received: $3 ech
|
387, 31134
|
bash, command-line-arguments
|
<h1>Propagate all arguments in a Bash shell script</h1>
<p>I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.</p>
<p>For instance, my script name is <code>foo.sh</code> and calls <code>bar.sh</code>.</p>
<p>foo.sh:</p>
<pre><code>bar $1 $2 $3 $4
</code></pre>
<p>How can I do this without explicitly specifying each parameter?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 54
|
bash
|
# Propagate all arguments in a Bash shell script
I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.
For instance, my script name is `foo.sh` and calls `bar.sh`.
foo.sh:
```
bar $1 $2 $3 $4
```
How can I do this without explicitly specifying each parameter?
|
Use `"$@"` instead of plain `$@` if you actually wish your parameters to be passed exactly as is.
Observe:
```
$ cat no_quotes.sh
#!/bin/bash
./echo_args.sh $@
$ cat quotes.sh
#!/bin/bash
./echo_args.sh "$@"
$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4
$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:
$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:
```
|
255898
|
How to iterate over arguments in a Bash script
| 1,205
|
2008-11-01 18:14:21
|
<p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p>
<pre><code>foo $1 args -o $1.ext
</code></pre>
<p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p>
<p>And, of course, I want to handle filenames with spaces in them.</p>
| 968,520
| 12,874
|
2023-07-31 17:02:04
| 255,913
| 2,010
|
2008-11-01 18:25:27
| 25,222
|
2023-07-31 17:02:04
|
https://stackoverflow.com/q/255898
|
https://stackoverflow.com/a/255913
|
<p>Use <code>"$@"</code> to represent all the arguments:</p>
<pre><code>for var in "$@"
do
echo "$var"
done
</code></pre>
<p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them:</p>
<pre><code>sh test.sh 1 2 '3 4'
1
2
3 4
</code></pre>
|
<p>Use <code>"$@"</code> to represent all the arguments:</p> <pre><code>for var in "$@" do echo "$var" done </code></pre> <p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them:</p> <pre><code>sh test.sh 1 2 '3 4' 1 2 3 4 </code></pr
|
387, 1231
|
bash, command-line
|
<h1>How to iterate over arguments in a Bash script</h1>
<p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p>
<pre><code>foo $1 args -o $1.ext
</code></pre>
<p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p>
<p>And, of course, I want to handle filenames with spaces in them.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 55
|
bash
|
# How to iterate over arguments in a Bash script
I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of `$1` easily:
```
foo $1 args -o $1.ext
```
I want to be able to pass multiple input names to the script. What's the right way to do it?
And, of course, I want to handle filenames with spaces in them.
|
Use `"$@"` to represent all the arguments:
```
for var in "$@"
do
echo "$var"
done
```
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them:
```
sh test.sh 1 2 '3 4'
1
2
3 4
```
|
1250079
|
How to escape single quotes within single quoted strings
| 1,494
|
2009-08-08 22:50:10
|
<p>Let's say, you have a Bash <code>alias</code> like:</p>
<pre><code>alias rxvt='urxvt'
</code></pre>
<p>which works fine.</p>
<p>However:</p>
<pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111''
</code></pre>
<p>won't work, and neither will:</p>
<pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
</code></pre>
<p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p>
<pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
</code></pre>
<p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p>
| 813,241
| 152,404
|
2025-05-29 14:58:14
| 1,250,279
| 2,002
|
2009-08-09 00:52:37
| 42,610
|
2024-03-11 23:33:18
|
https://stackoverflow.com/q/1250079
|
https://stackoverflow.com/a/1250279
|
<p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p>
<pre><code> alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234
</code></pre>
<p>Explanation of how <code>'"'"'</code> is interpreted as just <code>'</code>:</p>
<ol>
<li><code>'</code> End first quotation which uses single quotes.</li>
<li><code>"</code> Start second quotation, using double-quotes.</li>
<li><code>'</code> Quoted character.</li>
<li><code>"</code> End second quotation, using double-quotes.</li>
<li><code>'</code> Start third quotation, using single quotes.</li>
</ol>
<p>If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word:</p>
<pre><code>$ echo 'abc''123'
abc123
$ echo 'abc'\''123'
abc'123
$ echo 'abc'"'"'123'
abc'123
</code></pre>
<p>It will also keep the internal representation with 'to be joined' strings, and will also prefer the shorter escape syntax when possible:</p>
<pre><code>$ alias test='echo '"'"'hi'"'"
$ alias test
alias test='echo '\''hi'\'''
$ test
hi
</code></pre>
|
<p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p> <pre><code> alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'" # ^^^^^ ^^^^^ ^^^^^ ^^^^ # 12345 12345 12345 1234 </code></pre> <p>Explanation of
|
367, 387, 10804
|
bash, quoting, syntax
|
<h1>How to escape single quotes within single quoted strings</h1>
<p>Let's say, you have a Bash <code>alias</code> like:</p>
<pre><code>alias rxvt='urxvt'
</code></pre>
<p>which works fine.</p>
<p>However:</p>
<pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111''
</code></pre>
<p>won't work, and neither will:</p>
<pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
</code></pre>
<p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p>
<pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
</code></pre>
<p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 56
|
bash
|
# How to escape single quotes within single quoted strings
Let's say, you have a Bash `alias` like:
```
alias rxvt='urxvt'
```
which works fine.
However:
```
alias rxvt='urxvt -fg '#111111' -bg '#111111''
```
won't work, and neither will:
```
alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
```
So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?
```
alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
```
seems ungainly although it would represent the same string if you're allowed to concatenate them like that.
|
If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:
```
alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234
```
Explanation of how `'"'"'` is interpreted as just `'`:
1. `'` End first quotation which uses single quotes.
2. `"` Start second quotation, using double-quotes.
3. `'` Quoted character.
4. `"` End second quotation, using double-quotes.
5. `'` Start third quotation, using single quotes.
If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word:
```
$ echo 'abc''123'
abc123
$ echo 'abc'\''123'
abc'123
$ echo 'abc'"'"'123'
abc'123
```
It will also keep the internal representation with 'to be joined' strings, and will also prefer the shorter escape syntax when possible:
```
$ alias test='echo '"'"'hi'"'"
$ alias test
alias test='echo '\''hi'\'''
$ test
hi
```
|
1951506
|
Add a new element to an array without specifying the index in Bash
| 1,038
|
2009-12-23 08:59:32
|
<p>Is there a way to do something like PHPs <code>$array[] = 'foo';</code> in bash vs doing:</p>
<pre><code>array[0]='foo'
array[1]='bar'
</code></pre>
| 909,436
| 5,441
|
2024-07-02 11:49:21
| 1,951,523
| 1,991
|
2009-12-23 09:02:55
| 172,594
|
2022-04-01 11:41:05
|
https://stackoverflow.com/q/1951506
|
https://stackoverflow.com/a/1951523
|
<p>Yes there is:</p>
<pre><code>ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
</code></pre>
<p><a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameters" rel="noreferrer">Bash Reference Manual</a>:</p>
<blockquote>
<p>In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.</p>
</blockquote>
<p>Also:</p>
<blockquote>
<p>When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays)</p>
</blockquote>
|
<p>Yes there is:</p> <pre><code>ARRAY=() ARRAY+=('foo') ARRAY+=('bar') </code></pre> <p><a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameters" rel="noreferrer">Bash Reference Manual</a>:</p> <blockquote> <p>In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to
|
114, 387
|
arrays, bash
|
<h1>Add a new element to an array without specifying the index in Bash</h1>
<p>Is there a way to do something like PHPs <code>$array[] = 'foo';</code> in bash vs doing:</p>
<pre><code>array[0]='foo'
array[1]='bar'
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 57
|
bash
|
# Add a new element to an array without specifying the index in Bash
Is there a way to do something like PHPs `$array[] = 'foo';` in bash vs doing:
```
array[0]='foo'
array[1]='bar'
```
|
Yes there is:
```
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
```
[Bash Reference Manual](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameters):
> In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.
Also:
> When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays)
|
4760215
|
Running shell command and capturing the output
| 1,489
|
2011-01-21 14:55:44
|
<p>I want to write a function that will execute a shell command and return its output <strong>as a string</strong>, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.</p>
<p>What would be a code example that would do such a thing?</p>
<p>For example:</p>
<pre><code>def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
</code></pre>
| 2,033,620
| 303,513
|
2025-05-30 19:46:28
| 4,760,517
| 1,965
|
2011-01-21 15:27:52
| 577,088
|
2021-12-19 11:14:18
|
https://stackoverflow.com/q/4760215
|
https://stackoverflow.com/a/4760517
|
<p>In all officially maintained versions of Python, the simplest approach is to use the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="noreferrer"><code>subprocess.check_output</code></a> function:</p>
<pre><code>>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p><code>check_output</code> runs a single program that takes only arguments as input.<sup>1</sup> It returns the result exactly as printed to <code>stdout</code>. If you need to write input to <code>stdin</code>, skip ahead to the <code>run</code> or <code>Popen</code> sections. If you want to execute complex shell commands, see the note on <code>shell=True</code> at the end of this answer.</p>
<p>The <code>check_output</code> function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.</p>
<h3>Modern versions of Python (3.5 or higher): <code>run</code></h3>
<p>If you're using <strong>Python 3.5+</strong>, and <strong>do not need backwards compatibility</strong>, the new <a href="https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module" rel="noreferrer"><code>run</code></a> function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the <a href="https://docs.python.org/3/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> module. To capture the output of a program, pass the <code>subprocess.PIPE</code> flag to the <code>stdout</code> keyword argument. Then access the <code>stdout</code> attribute of the returned <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess" rel="noreferrer"><code>CompletedProcess</code></a> object:</p>
<pre><code>>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>The return value is a <code>bytes</code> object, so if you want a proper string, you'll need to <code>decode</code> it. Assuming the called process returns a UTF-8-encoded string:</p>
<pre><code>>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>This can all be compressed to a one-liner if desired:</p>
<pre><code>>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>If you want to pass input to the process's <code>stdin</code>, you can pass a <code>bytes</code> object to the <code>input</code> keyword argument:</p>
<pre><code>>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'
</code></pre>
<p>You can capture errors by passing <code>stderr=subprocess.PIPE</code> (capture to <code>result.stderr</code>) or <code>stderr=subprocess.STDOUT</code> (capture to <code>result.stdout</code> along with regular output). If you want <code>run</code> to throw an exception when the process returns a nonzero exit code, you can pass <code>check=True</code>. (Or you can check the <code>returncode</code> attribute of <code>result</code> above.) When security is not a concern, you can also run more complex shell commands by passing <code>shell=True</code> as described at the end of this answer.</p>
<p>Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:</p>
<pre><code>>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>Using <code>run</code> this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the <code>run</code> function alone.</p>
<h3>Older versions of Python (3-3.4): more about <code>check_output</code></h3>
<p>If you are using an older version of Python, or need modest backwards compatibility, you can use the <code>check_output</code> function as briefly described above. It has been available since Python 2.7.</p>
<pre><code>subprocess.check_output(*popenargs, **kwargs)
</code></pre>
<p>It takes takes the same arguments as <code>Popen</code> (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, <code>check_output</code> is equivalent to executing <code>run</code> with <code>check=True</code> and <code>stdout=PIPE</code>, and returning just the <code>stdout</code> attribute.</p>
<p>You can pass <code>stderr=subprocess.STDOUT</code> to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing <code>shell=True</code> as described at the end of this answer.</p>
<p>If you need to pipe from <code>stderr</code> or pass input to the process, <code>check_output</code> won't be up to the task. See the <code>Popen</code> examples below in that case.</p>
<h3>Complex applications and legacy versions of Python (2.6 and below): <code>Popen</code></h3>
<p>If you need deep backwards compatibility, or if you need more sophisticated functionality than <code>check_output</code> or <code>run</code> provide, you'll have to work directly with <code>Popen</code> objects, which encapsulate the low-level API for subprocesses.</p>
<p>The <code>Popen</code> constructor accepts either <strong>a single command</strong> without arguments, or <strong>a list</strong> containing a command as its first item, followed by any number of arguments, each as a separate item in the list. <a href="https://docs.python.org/3/library/shlex.html" rel="noreferrer"><code>shlex.split</code></a> can help parse strings into appropriately formatted lists. <code>Popen</code> objects also accept a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="noreferrer">host of different arguments</a> for process IO management and low-level configuration.</p>
<p>To send input and capture output, <code>communicate</code> is almost always the preferred method. As in:</p>
<pre><code>output = subprocess.Popen(["mycmd", "myarg"],
stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>Or</p>
<pre><code>>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE,
... stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo
</code></pre>
<p>If you set <code>stdin=PIPE</code>, <code>communicate</code> also allows you to pass data to the process via <code>stdin</code>:</p>
<pre><code>>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo
</code></pre>
<p>Note <a href="https://stackoverflow.com/a/21867841/577088">Aaron Hall's answer</a>, which indicates that on some systems, you may need to set <code>stdout</code>, <code>stderr</code>, and <code>stdin</code> all to <code>PIPE</code> (or <code>DEVNULL</code>) to get <code>communicate</code> to work at all.</p>
<p>In some rare cases, you may need complex, real-time output capturing. <a href="https://stackoverflow.com/a/4760274/577088">Vartec</a>'s answer suggests a way forward, but methods other than <code>communicate</code> are prone to deadlocks if not used carefully.</p>
<p>As with all the above functions, when security is not a concern, you can run more complex shell commands by passing <code>shell=True</code>.</p>
<h3>Notes</h3>
<p><strong>1. Running shell commands: the <code>shell=True</code> argument</strong></p>
<p>Normally, each call to <code>run</code>, <code>check_output</code>, or the <code>Popen</code> constructor executes a <em>single program</em>. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass <code>shell=True</code>, which all three functions support. For example:</p>
<pre><code>>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'
</code></pre>
<p>However, doing this raises <a href="https://docs.python.org/3/library/subprocess.html#security-considerations" rel="noreferrer">security concerns</a>. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via</p>
<pre><code>run(cmd, [stdout=etc...], input=other_output)
</code></pre>
<p>Or</p>
<pre><code>Popen(cmd, [stdout=etc...]).communicate(other_output)
</code></pre>
<p>The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like <a href="https://stackoverflow.com/questions/6341451/piping-together-several-subprocesses">this</a>.</p>
|
<p>In all officially maintained versions of Python, the simplest approach is to use the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="noreferrer"><code>subprocess.check_output</code></a> function:</p> <pre><code>>>> subprocess.check_output(['ls', '-l']) b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n' </code></pre> <p><code>check
|
16, 390, 2348
|
python, shell, subprocess
|
<h1>Running shell command and capturing the output</h1>
<p>I want to write a function that will execute a shell command and return its output <strong>as a string</strong>, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.</p>
<p>What would be a code example that would do such a thing?</p>
<p>For example:</p>
<pre><code>def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 58
|
bash
|
# Running shell command and capturing the output
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.
What would be a code example that would do such a thing?
For example:
```
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
```
|
In all officially maintained versions of Python, the simplest approach is to use the [`subprocess.check_output`](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) function:
```
>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
```
`check_output` runs a single program that takes only arguments as input.1 It returns the result exactly as printed to `stdout`. If you need to write input to `stdin`, skip ahead to the `run` or `Popen` sections. If you want to execute complex shell commands, see the note on `shell=True` at the end of this answer.
The `check_output` function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.
### Modern versions of Python (3.5 or higher): `run`
If you're using **Python 3.5+**, and **do not need backwards compatibility**, the new [`run`](https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module) function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the [`subprocess`](https://docs.python.org/3/library/subprocess.html) module. To capture the output of a program, pass the `subprocess.PIPE` flag to the `stdout` keyword argument. Then access the `stdout` attribute of the returned [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) object:
```
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
```
The return value is a `bytes` object, so if you want a proper string, you'll need to `decode` it. Assuming the called process returns a UTF-8-encoded string:
```
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
```
This can all be compressed to a one-liner if desired:
```
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
```
If you want to pass input to the process's `stdin`, you can pass a `bytes` object to the `input` keyword argument:
```
>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'
```
You can capture errors by passing `stderr=subprocess.PIPE` (capture to `result.stderr`) or `stderr=subprocess.STDOUT` (capture to `result.stdout` along with regular output). If you want `run` to throw an exception when the process returns a nonzero exit code, you can pass `check=True`. (Or you can check the `returncode` attribute of `result` above.) When security is not a concern, you can also run more complex shell commands by passing `shell=True` as described at the end of this answer.
Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:
```
>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
```
Using `run` this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the `run` function alone.
### Older versions of Python (3-3.4): more about `check_output`
If you are using an older version of Python, or need modest backwards compatibility, you can use the `check_output` function as briefly described above. It has been available since Python 2.7.
```
subprocess.check_output(*popenargs, **kwargs)
```
It takes takes the same arguments as `Popen` (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, `check_output` is equivalent to executing `run` with `check=True` and `stdout=PIPE`, and returning just the `stdout` attribute.
You can pass `stderr=subprocess.STDOUT` to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing `shell=True` as described at the end of this answer.
If you need to pipe from `stderr` or pass input to the process, `check_output` won't be up to the task. See the `Popen` examples below in that case.
### Complex applications and legacy versions of Python (2.6 and below): `Popen`
If you need deep backwards compatibility, or if you need more sophisticated functionality than `check_output` or `run` provide, you'll have to work directly with `Popen` objects, which encapsulate the low-level API for subprocesses.
The `Popen` constructor accepts either **a single command** without arguments, or **a list** containing a command as its first item, followed by any number of arguments, each as a separate item in the list. [`shlex.split`](https://docs.python.org/3/library/shlex.html) can help parse strings into appropriately formatted lists. `Popen` objects also accept a [host of different arguments](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) for process IO management and low-level configuration.
To send input and capture output, `communicate` is almost always the preferred method. As in:
```
output = subprocess.Popen(["mycmd", "myarg"],
stdout=subprocess.PIPE).communicate()[0]
```
Or
```
>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE,
... stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo
```
If you set `stdin=PIPE`, `communicate` also allows you to pass data to the process via `stdin`:
```
>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo
```
Note [Aaron Hall's answer](https://stackoverflow.com/a/21867841/577088), which indicates that on some systems, you may need to set `stdout`, `stderr`, and `stdin` all to `PIPE` (or `DEVNULL`) to get `communicate` to work at all.
In some rare cases, you may need complex, real-time output capturing. [Vartec](https://stackoverflow.com/a/4760274/577088)'s answer suggests a way forward, but methods other than `communicate` are prone to deadlocks if not used carefully.
As with all the above functions, when security is not a concern, you can run more complex shell commands by passing `shell=True`.
### Notes
**1. Running shell commands: the `shell=True` argument**
Normally, each call to `run`, `check_output`, or the `Popen` constructor executes a *single program*. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass `shell=True`, which all three functions support. For example:
```
>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'
```
However, doing this raises [security concerns](https://docs.python.org/3/library/subprocess.html#security-considerations). If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via
```
run(cmd, [stdout=etc...], input=other_output)
```
Or
```
Popen(cmd, [stdout=etc...]).communicate(other_output)
```
The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like [this](https://stackoverflow.com/questions/6341451/piping-together-several-subprocesses).
|
9157138
|
Recursively counting files in a Linux directory
| 1,146
|
2012-02-06 07:59:18
|
<p>How can I recursively count files in a Linux directory?</p>
<p>I found this:</p>
<pre><code>find DIR_NAME -type f ¦ wc -l
</code></pre>
<p>But when I run this it returns the following error.</p>
<blockquote>
<p>find: paths must precede expression: ¦</p>
</blockquote>
| 1,012,597
| 1,010,718
|
2025-02-04 18:47:36
| 9,157,162
| 1,949
|
2012-02-06 08:02:30
| 421,195
|
2016-09-20 10:13:15
|
https://stackoverflow.com/q/9157138
|
https://stackoverflow.com/a/9157162
|
<p>This should work:</p>
<pre><code>find DIR_NAME -type f | wc -l
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>-type f</code> to include only files.</li>
<li><code>|</code> (<strong>and not <code>¦</code></strong>) redirects <code>find</code> command's standard output to <code>wc</code> command's standard input.</li>
<li><code>wc</code> (short for word count) counts newlines, words and bytes on its input (<a href="http://man7.org/linux/man-pages/man1/wc.1.html" rel="noreferrer">docs</a>).</li>
<li><code>-l</code> to count just newlines.</li>
</ul>
<p><strong>Notes:</strong> </p>
<ul>
<li>Replace <code>DIR_NAME</code> with <code>.</code> to execute the command in the current folder.</li>
<li>You can also remove the <code>-type f</code> to include directories (and symlinks) in the count.</li>
<li>It's possible this command will overcount if filenames can contain newline characters.</li>
</ul>
<p><strong>Explanation of why your example does not work:</strong></p>
<p>In the command you showed, you do not use the "Pipe" (<code>|</code>) to kind-of connect two commands, but the broken bar (<code>¦</code>) which the shell does not recognize as a command or something similar. That's why you get that error message.</p>
|
<p>This should work:</p> <pre><code>find DIR_NAME -type f | wc -l </code></pre> <p><strong>Explanation:</strong></p> <ul> <li><code>-type f</code> to include only files.</li> <li><code>|</code> (<strong>and not <code>¦</code></strong>) redirects <code>find</code> command's standard output to <code>wc</code> command's standard input.</li> <li><code>wc</code> (short for word count) counts newline
|
58, 387
|
bash, linux
|
<h1>Recursively counting files in a Linux directory</h1>
<p>How can I recursively count files in a Linux directory?</p>
<p>I found this:</p>
<pre><code>find DIR_NAME -type f ¦ wc -l
</code></pre>
<p>But when I run this it returns the following error.</p>
<blockquote>
<p>find: paths must precede expression: ¦</p>
</blockquote>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 59
|
bash
|
# Recursively counting files in a Linux directory
How can I recursively count files in a Linux directory?
I found this:
```
find DIR_NAME -type f ¦ wc -l
```
But when I run this it returns the following error.
> find: paths must precede expression: ¦
|
This should work:
```
find DIR_NAME -type f | wc -l
```
**Explanation:**
- `-type f` to include only files.
- `|` (**and not `¦`**) redirects `find` command's standard output to `wc` command's standard input.
- `wc` (short for word count) counts newlines, words and bytes on its input ([docs](http://man7.org/linux/man-pages/man1/wc.1.html)).
- `-l` to count just newlines.
**Notes:**
- Replace `DIR_NAME` with `.` to execute the command in the current folder.
- You can also remove the `-type f` to include directories (and symlinks) in the count.
- It's possible this command will overcount if filenames can contain newline characters.
**Explanation of why your example does not work:**
In the command you showed, you do not use the "Pipe" (`|`) to kind-of connect two commands, but the broken bar (`¦`) which the shell does not recognize as a command or something similar. That's why you get that error message.
|
54429210
|
How do I prevent Conda from activating the base environment by default?
| 920
|
2019-01-29 20:37:00
|
<p>I recently installed anaconda2 on my Mac. By default Conda is configured to activate the base environment when I open a fresh terminal session.</p>
<p>I want access to the Conda commands (i.e. I want the path to Conda added to my <code>$PATH</code> which Conda does when initialised so that's fine).</p>
<p>However I don't ordinarily program in python, and I don't want Conda to activate the base environment by default.</p>
<p>When first executing <code>conda init</code> from the prompt, Conda adds the following to my <code>.bash_profile</code>:</p>
<pre><code># >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
unset __conda_setup
# <<< conda initialize <<<
</code></pre>
<p>If I comment out the whole block, then I can't activate any Conda environments.</p>
<p>I tried to comment out the whole block except for</p>
<pre><code>export PATH="/Users/geoff/anaconda2/bin:$PATH"
</code></pre>
<p>But then when I started a new session and tried to activate an environment, I got this error message:</p>
<pre><code>CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
</code></pre>
<p><a href="https://askubuntu.com/questions/849470/how-do-i-activate-a-conda-environment-in-my-bashrc">This question</a> (and others like it) are helpful, but doesn't ultimately answer my question and is more suited for linux users.</p>
<p>To be clear, I'm not asking to remove the <code>(base)</code> from my <code>$PS1</code> I'm asking for Conda not to activate base when I open a terminal session.</p>
| 645,791
| 6,137,027
|
2025-07-09 15:04:23
| 54,560,785
| 1,932
|
2019-02-06 19:01:25
| 11,024,693
|
2021-09-13 13:43:48
|
https://stackoverflow.com/q/54429210
|
https://stackoverflow.com/a/54560785
|
<p>I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:</p>
<pre><code>conda config --set auto_activate_base false
</code></pre>
<p>The first time you run it, it'll create a <code>.condarc</code> in your home directory with that setting to override the default.</p>
<p>This wouldn't de-clutter your <code>.bash_profile</code> but it's a cleaner solution without manual editing that section that conda manages.</p>
|
<p>I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:</p> <pre><code>conda config --set auto_activate_base false </code></pre> <p>The first time you run it, it'll create a <code>.condarc</code> in your home directory with that setting to override the default.</p> <p>This wouldn't de-clut
|
387, 96537
|
bash, conda
|
<h1>How do I prevent Conda from activating the base environment by default?</h1>
<p>I recently installed anaconda2 on my Mac. By default Conda is configured to activate the base environment when I open a fresh terminal session.</p>
<p>I want access to the Conda commands (i.e. I want the path to Conda added to my <code>$PATH</code> which Conda does when initialised so that's fine).</p>
<p>However I don't ordinarily program in python, and I don't want Conda to activate the base environment by default.</p>
<p>When first executing <code>conda init</code> from the prompt, Conda adds the following to my <code>.bash_profile</code>:</p>
<pre><code># >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
unset __conda_setup
# <<< conda initialize <<<
</code></pre>
<p>If I comment out the whole block, then I can't activate any Conda environments.</p>
<p>I tried to comment out the whole block except for</p>
<pre><code>export PATH="/Users/geoff/anaconda2/bin:$PATH"
</code></pre>
<p>But then when I started a new session and tried to activate an environment, I got this error message:</p>
<pre><code>CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
</code></pre>
<p><a href="https://askubuntu.com/questions/849470/how-do-i-activate-a-conda-environment-in-my-bashrc">This question</a> (and others like it) are helpful, but doesn't ultimately answer my question and is more suited for linux users.</p>
<p>To be clear, I'm not asking to remove the <code>(base)</code> from my <code>$PS1</code> I'm asking for Conda not to activate base when I open a terminal session.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 60
|
bash
|
# How do I prevent Conda from activating the base environment by default?
I recently installed anaconda2 on my Mac. By default Conda is configured to activate the base environment when I open a fresh terminal session.
I want access to the Conda commands (i.e. I want the path to Conda added to my `$PATH` which Conda does when initialised so that's fine).
However I don't ordinarily program in python, and I don't want Conda to activate the base environment by default.
When first executing `conda init` from the prompt, Conda adds the following to my `.bash_profile`:
```
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
unset __conda_setup
# <<< conda initialize <<<
```
If I comment out the whole block, then I can't activate any Conda environments.
I tried to comment out the whole block except for
```
export PATH="/Users/geoff/anaconda2/bin:$PATH"
```
But then when I started a new session and tried to activate an environment, I got this error message:
```
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
```
[This question](https://askubuntu.com/questions/849470/how-do-i-activate-a-conda-environment-in-my-bashrc) (and others like it) are helpful, but doesn't ultimately answer my question and is more suited for linux users.
To be clear, I'm not asking to remove the `(base)` from my `$PS1` I'm asking for Conda not to activate base when I open a terminal session.
|
I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:
```
conda config --set auto_activate_base false
```
The first time you run it, it'll create a `.condarc` in your home directory with that setting to override the default.
This wouldn't de-clutter your `.bash_profile` but it's a cleaner solution without manual editing that section that conda manages.
|
2237080
|
How to compare strings in Bash
| 1,354
|
2010-02-10 13:31:18
|
<p>How do I compare a variable to a string (and do something if they match)?</p>
| 1,817,067
| 243,967
|
2024-06-26 17:37:19
| 2,237,103
| 1,889
|
2010-02-10 13:34:55
| 75,170
|
2020-01-01 13:55:45
|
https://stackoverflow.com/q/2237080
|
https://stackoverflow.com/a/2237103
|
<h1>Using variables in if statements</h1>
<pre><code>if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
</code></pre>
<p>If you want to do something when they don't match, replace <code>=</code> with <code>!=</code>. You can read more about <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.1" rel="noreferrer">string operations</a> and <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.3" rel="noreferrer">arithmetic operations</a> in their respective documentation.</p>
<h3>Why do we use quotes around <code>$x</code>?</h3>
<p>You want the quotes around <code>$x</code>, because if it is empty, your Bash script encounters a syntax error as seen below:</p>
<pre><code>if [ = "valid" ]; then
</code></pre>
<hr>
<h3>Non-standard use of <code>==</code> operator</h3>
<p>Note that Bash allows <code>==</code> to be used for equality with <code>[</code>, but <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html" rel="noreferrer">this is not standard</a>.</p>
<p>Use either the first case wherein the quotes around <code>$x</code> are optional:</p>
<pre><code>if [[ "$x" == "valid" ]]; then
</code></pre>
<p>or use the second case:</p>
<pre><code>if [ "$x" = "valid" ]; then
</code></pre>
|
<h1>Using variables in if statements</h1> <pre><code>if [ "$x" = "valid" ]; then echo "x has the value 'valid'" fi </code></pre> <p>If you want to do something when they don't match, replace <code>=</code> with <code>!=</code>. You can read more about <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.1" rel="noreferrer">string operations</a> and <a href="http://tldp.org/HOWTO/B
|
139, 387
|
bash, string
|
<h1>How to compare strings in Bash</h1>
<p>How do I compare a variable to a string (and do something if they match)?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 61
|
bash
|
# How to compare strings in Bash
How do I compare a variable to a string (and do something if they match)?
|
# Using variables in if statements
```
if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
```
If you want to do something when they don't match, replace `=` with `!=`. You can read more about [string operations](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.1) and [arithmetic operations](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.3) in their respective documentation.
### Why do we use quotes around `$x`?
You want the quotes around `$x`, because if it is empty, your Bash script encounters a syntax error as seen below:
```
if [ = "valid" ]; then
```
---
### Non-standard use of `==` operator
Note that Bash allows `==` to be used for equality with `[`, but [this is not standard](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html).
Use either the first case wherein the quotes around `$x` are optional:
```
if [[ "$x" == "valid" ]]; then
```
or use the second case:
```
if [ "$x" = "valid" ]; then
```
|
4210042
|
How do I exclude a directory when using `find`?
| 2,329
|
2010-11-17 22:57:02
|
<p>How do I exclude a specific directory when searching for <code>*.js</code> files using <code>find</code>?</p>
<pre><code>find . -name '*.js'
</code></pre>
| 2,032,695
| 143,269
|
2025-07-31 21:11:57
| 4,210,072
| 1,860
|
2010-11-17 23:00:42
| 164,839
|
2025-07-31 21:09:25
|
https://stackoverflow.com/q/4210042
|
https://stackoverflow.com/a/4210072
|
<p>Use the <code>-prune</code> primary. For example, if you want to exclude <code>./misc</code>:</p>
<pre class="lang-none prettyprint-override"><code>find . -path ./misc -prune -o -name '*.txt' -print
</code></pre>
<p>Note that the final <code>-print</code> is <strong>needed</strong> to avoid printing out <code>./misc</code>. See <a href="https://stackoverflow.com/a/57779016/5267751">cycollins's answer</a> for the explanation why.</p>
<p>To exclude multiple directories, OR them between parentheses.</p>
<pre class="lang-none prettyprint-override"><code>find . -type d \( -path ./dir1 -o -path ./dir2 -o -path ./dir3 \) -prune -o -name '*.txt' -print
</code></pre>
<p>And, to exclude directories with a specific name at any level, use the <code>-name</code> primary instead of <code>-path</code>.</p>
<pre class="lang-none prettyprint-override"><code>find . -type d -name node_modules -prune -o -name '*.json' -print
</code></pre>
|
<p>Use the <code>-prune</code> primary. For example, if you want to exclude <code>./misc</code>:</p> <pre class="lang-none prettyprint-override"><code>find . -path ./misc -prune -o -name '*.txt' -print </code></pre> <p>Note that the final <code>-print</code> is <strong>needed</strong> to avoid printing out <code>./misc</code>. See <a href="https://stackoverflow.com/a/57779016/5267751">cycollins's
|
58, 390, 10193
|
find, linux, shell
|
<h1>How do I exclude a directory when using `find`?</h1>
<p>How do I exclude a specific directory when searching for <code>*.js</code> files using <code>find</code>?</p>
<pre><code>find . -name '*.js'
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 62
|
bash
|
# How do I exclude a directory when using `find`?
How do I exclude a specific directory when searching for `*.js` files using `find`?
```
find . -name '*.js'
```
|
Use the `-prune` primary. For example, if you want to exclude `./misc`:
```
find . -path ./misc -prune -o -name '*.txt' -print
```
Note that the final `-print` is **needed** to avoid printing out `./misc`. See [cycollins's answer](https://stackoverflow.com/a/57779016/5267751) for the explanation why.
To exclude multiple directories, OR them between parentheses.
```
find . -type d \( -path ./dir1 -o -path ./dir2 -o -path ./dir3 \) -prune -o -name '*.txt' -print
```
And, to exclude directories with a specific name at any level, use the `-name` primary instead of `-path`.
```
find . -type d -name node_modules -prune -o -name '*.json' -print
```
|
8987037
|
How to kill all processes with a given partial name?
| 892
|
2012-01-24 12:46:13
|
<p>I want to kill all processes that I get by:</p>
<pre><code>ps aux | grep my_pattern
</code></pre>
<p>How to do it?</p>
<p>This does not work:</p>
<pre><code>pkill my_pattern
</code></pre>
| 786,555
| 61,342
|
2024-06-04 10:34:04
| 8,987,063
| 1,837
|
2012-01-24 12:47:56
| 1,071,684
|
2021-09-06 20:26:07
|
https://stackoverflow.com/q/8987037
|
https://stackoverflow.com/a/8987063
|
<p>Use <code>pkill -f</code>, which matches the pattern for any part of the command line</p>
<pre><code>pkill -f my_pattern
</code></pre>
<p>Just in case it doesn't work, try to use this one as well:</p>
<pre><code>pkill -9 -f my_pattern
</code></pre>
|
<p>Use <code>pkill -f</code>, which matches the pattern for any part of the command line</p> <pre><code>pkill -f my_pattern </code></pre> <p>Just in case it doesn't work, try to use this one as well:</p> <pre><code>pkill -9 -f my_pattern </code></pre>
|
58, 387, 1993
|
bash, linux, posix
|
<h1>How to kill all processes with a given partial name?</h1>
<p>I want to kill all processes that I get by:</p>
<pre><code>ps aux | grep my_pattern
</code></pre>
<p>How to do it?</p>
<p>This does not work:</p>
<pre><code>pkill my_pattern
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 63
|
bash
|
# How to kill all processes with a given partial name?
I want to kill all processes that I get by:
```
ps aux | grep my_pattern
```
How to do it?
This does not work:
```
pkill my_pattern
```
|
Use `pkill -f`, which matches the pattern for any part of the command line
```
pkill -f my_pattern
```
Just in case it doesn't work, try to use this one as well:
```
pkill -9 -f my_pattern
```
|
2953646
|
How can I declare and use Boolean variables in a shell script?
| 1,550
|
2010-06-01 21:54:53
|
<p>I tried to declare a Boolean variable in a shell script using the following syntax:</p>
<pre><code>variable=$false
variable=$true
</code></pre>
<p>Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?</p>
<pre><code>if [ $variable ]
if [ !$variable ]
</code></pre>
| 1,894,028
| 355,896
|
2024-12-13 13:08:33
| 2,953,673
| 1,824
|
2010-06-01 21:58:55
| 89,391
|
2024-12-01 21:56:33
|
https://stackoverflow.com/q/2953646
|
https://stackoverflow.com/a/2953673
|
<p><strong>Revised Answer (Feb 12, 2014)</strong></p>
<pre><code>the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
echo 'Be careful not to fall off!'
fi
</code></pre>
<hr />
<p><strong>Original Answer</strong></p>
<p>Caveats: <a href="https://stackoverflow.com/a/21210966/89391">https://stackoverflow.com/a/21210966/89391</a></p>
<pre><code>the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
echo 'Be careful not to fall off!'
fi
</code></pre>
<p>From: <a href="https://github.com/aperezdc/perezdecastro.org/blob/master/stash/using-boolean-variables-in-bash.markdown" rel="noreferrer">Using boolean variables in Bash</a></p>
<p><em>The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, <a href="https://stackoverflow.com/users/26428/dennis-williamson">Dennis Williamson's comment</a> about Bash's builtin <a href="https://pubs.opengroup.org/onlinepubs/9799919799/" rel="noreferrer"><code>true</code></a> on Jun 2, 2010 only applies to the original answer, not the revised.</em></p>
|
<p><strong>Revised Answer (Feb 12, 2014)</strong></p> <pre><code>the_world_is_flat=true # ...do something interesting... if [ "$the_world_is_flat" = true ] ; then echo 'Be careful not to fall off!' fi </code></pre> <hr /> <p><strong>Original Answer</strong></p> <p>Caveats: <a href="https://stackoverflow.com/a/21210966/89391">https://stackoverflow.com/a/21210966/89391</a></p> <pre><co
|
387, 390, 531, 2848, 10327
|
bash, boolean, scripting, sh, shell
|
<h1>How can I declare and use Boolean variables in a shell script?</h1>
<p>I tried to declare a Boolean variable in a shell script using the following syntax:</p>
<pre><code>variable=$false
variable=$true
</code></pre>
<p>Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?</p>
<pre><code>if [ $variable ]
if [ !$variable ]
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 64
|
bash
|
# How can I declare and use Boolean variables in a shell script?
I tried to declare a Boolean variable in a shell script using the following syntax:
```
variable=$false
variable=$true
```
Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?
```
if [ $variable ]
if [ !$variable ]
```
|
**Revised Answer (Feb 12, 2014)**
```
the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
echo 'Be careful not to fall off!'
fi
```
---
**Original Answer**
Caveats: <https://stackoverflow.com/a/21210966/89391>
```
the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
echo 'Be careful not to fall off!'
fi
```
From: [Using boolean variables in Bash](https://github.com/aperezdc/perezdecastro.org/blob/master/stash/using-boolean-variables-in-bash.markdown)
*The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, [Dennis Williamson's comment](https://stackoverflow.com/users/26428/dennis-williamson) about Bash's builtin [`true`](https://pubs.opengroup.org/onlinepubs/9799919799/) on Jun 2, 2010 only applies to the original answer, not the revised.*
|
10929453
|
Read a file line by line assigning the value to a variable
| 1,002
|
2012-06-07 09:49:09
|
<p>I have the following .txt file:</p>
<pre class="lang-none prettyprint-override"><code>Marco
Paolo
Antonio
</code></pre>
<p>I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is <code>$name</code>, the flow is:</p>
<ul>
<li>Read first line from file</li>
<li>Assign <code>$name</code> = "Marco"</li>
<li>Do some tasks with <code>$name</code></li>
<li>Read second line from file</li>
<li>Assign <code>$name</code> = "Paolo"</li>
</ul>
| 2,215,990
| 1,099,991
|
2019-10-31 17:33:09
| 10,929,511
| 1,794
|
2012-06-07 09:53:38
| 806,299
|
2019-10-31 17:33:09
|
https://stackoverflow.com/q/10929453
|
https://stackoverflow.com/a/10929511
|
<p>The following reads a file passed as an argument line by line:</p>
<pre><code>while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
</code></pre>
<p>This is the <a href="http://mywiki.wooledge.org/BashFAQ/001" rel="noreferrer">standard form</a> for reading lines from a file in a loop. Explanation:</p>
<ul>
<li><code>IFS=</code> (or <code>IFS=''</code>) prevents leading/trailing whitespace from being trimmed.</li>
<li><code>-r</code> prevents backslash escapes from being interpreted.</li>
</ul>
<p>Or you can put it in a bash file helper script, example contents:</p>
<pre><code>#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
</code></pre>
<p>If the above is saved to a script with filename <code>readfile</code>, it can be run as follows:</p>
<pre><code>chmod +x readfile
./readfile filename.txt
</code></pre>
<p>If the file isn’t a <a href="https://stackoverflow.com/a/729795/1968">standard POSIX text file</a> (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:</p>
<pre><code>while IFS= read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
</code></pre>
<p>Here, <code>|| [[ -n $line ]]</code> prevents the last line from being ignored if it doesn't end with a <code>\n</code> (since <code>read</code> returns a non-zero exit code when it encounters EOF).</p>
<p>If the commands inside the loop also read from standard input, the file descriptor used by <code>read</code> can be chanced to something else (avoid the <a href="https://en.wikipedia.org/wiki/File_descriptor" rel="noreferrer">standard file descriptors</a>), e.g.:</p>
<pre><code>while IFS= read -r -u3 line; do
echo "Text read from file: $line"
done 3< "$1"
</code></pre>
<p>(Non-Bash shells might not know <code>read -u3</code>; use <code>read <&3</code> instead.)</p>
|
<p>The following reads a file passed as an argument line by line:</p> <pre><code>while IFS= read -r line; do echo "Text read from file: $line" done < my_filename.txt </code></pre> <p>This is the <a href="http://mywiki.wooledge.org/BashFAQ/001" rel="noreferrer">standard form</a> for reading lines from a file in a loop. Explanation:</p> <ul> <li><code>IFS=</code> (or <code>IFS=''</code>) p
|
387
|
bash
|
<h1>Read a file line by line assigning the value to a variable</h1>
<p>I have the following .txt file:</p>
<pre class="lang-none prettyprint-override"><code>Marco
Paolo
Antonio
</code></pre>
<p>I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is <code>$name</code>, the flow is:</p>
<ul>
<li>Read first line from file</li>
<li>Assign <code>$name</code> = "Marco"</li>
<li>Do some tasks with <code>$name</code></li>
<li>Read second line from file</li>
<li>Assign <code>$name</code> = "Paolo"</li>
</ul>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 65
|
bash
|
# Read a file line by line assigning the value to a variable
I have the following .txt file:
```
Marco
Paolo
Antonio
```
I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is `$name`, the flow is:
- Read first line from file
- Assign `$name` = "Marco"
- Do some tasks with `$name`
- Read second line from file
- Assign `$name` = "Paolo"
|
The following reads a file passed as an argument line by line:
```
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
```
This is the [standard form](http://mywiki.wooledge.org/BashFAQ/001) for reading lines from a file in a loop. Explanation:
- `IFS=` (or `IFS=''`) prevents leading/trailing whitespace from being trimmed.
- `-r` prevents backslash escapes from being interpreted.
Or you can put it in a bash file helper script, example contents:
```
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
```
If the above is saved to a script with filename `readfile`, it can be run as follows:
```
chmod +x readfile
./readfile filename.txt
```
If the file isn’t a [standard POSIX text file](https://stackoverflow.com/a/729795/1968) (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:
```
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
```
Here, `|| [[ -n $line ]]` prevents the last line from being ignored if it doesn't end with a `\n` (since `read` returns a non-zero exit code when it encounters EOF).
If the commands inside the loop also read from standard input, the file descriptor used by `read` can be chanced to something else (avoid the [standard file descriptors](https://en.wikipedia.org/wiki/File_descriptor)), e.g.:
```
while IFS= read -r -u3 line; do
echo "Text read from file: $line"
done 3< "$1"
```
(Non-Bash shells might not know `read -u3`; use `read <&3` instead.)
|
1955505
|
Parsing JSON with Unix tools
| 1,318
|
2009-12-23 21:46:58
|
<p>I'm trying to parse JSON returned from a curl request, like so:</p>
<pre><code>curl 'http://twitter.com/users/username.json' |
sed -e 's/[{}]/''/g' |
awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
</code></pre>
<p>The above splits the JSON into fields, for example:</p>
<pre><code>% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...
</code></pre>
<p>How do I print a specific field (denoted by the <code>-v k=text</code>)?</p>
| 1,872,030
| 141,821
|
2025-03-09 08:30:48
| 1,955,555
| 1,791
|
2009-12-23 21:59:30
| 69,755
|
2022-02-08 12:30:29
|
https://stackoverflow.com/q/1955505
|
https://stackoverflow.com/a/1955555
|
<p>There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as <a href="https://stedolan.github.io/jq/" rel="noreferrer"><code>jq</code></a>:</p>
<pre><code>curl -s 'https://api.github.com/users/lambda' | jq -r '.name'
</code></pre>
<p>You can also do this with tools that are likely already installed on your system, like Python using the <a href="https://docs.python.org/2/library/json.html" rel="noreferrer"><code>json</code> module</a>, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:</p>
<p>Python 3:</p>
<pre><code>curl -s 'https://api.github.com/users/lambda' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"
</code></pre>
<p>Python 2:</p>
<pre><code>export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
python2 -c "import sys, json; print json.load(sys.stdin)['name']"
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>Why not a pure shell solution?</h3>
<p>The standard <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html" rel="noreferrer">POSIX/Single Unix Specification shell</a> is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are <a href="https://stackoverflow.com/questions/688849/associative-arrays-in-shell-scripts">somewhat hacky ways to do it</a>, but many of them can break if keys or values contain certain special characters.</p>
<p>Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.</p>
<p>Finally, writing a full fledged JSON parser in shell would be a significant enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.</p>
<h3>Why not use awk, sed, or grep?</h3>
<p>It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.</p>
<p>However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.</p>
<p>So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on <code>jq</code> or Python.</p>
<p>I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.</p>
<h2>Historical notes</h2>
<p>This answer originally recommended <a href="http://github.com/micha/jsawk" rel="noreferrer">jsawk</a>, which should still work, but is a little more cumbersome to use than <code>jq</code>, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:</p>
<pre><code>curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'
</code></pre>
<p>This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:</p>
<pre><code>curl 'http://twitter.com/users/username.json' | jq -r '.text'
</code></pre>
|
<p>There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as <a href="https://stedolan.github.io/jq/" rel="noreferrer"><code>jq</code></a>:</p> <pre><code>curl -s 'https://api.github.com/users/lambda' | jq -r '.name' </code></pre> <p>You can also do this with tools that ar
|
387, 1357, 1508, 105170
|
bash, jq, json, parsing
|
<h1>Parsing JSON with Unix tools</h1>
<p>I'm trying to parse JSON returned from a curl request, like so:</p>
<pre><code>curl 'http://twitter.com/users/username.json' |
sed -e 's/[{}]/''/g' |
awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
</code></pre>
<p>The above splits the JSON into fields, for example:</p>
<pre><code>% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...
</code></pre>
<p>How do I print a specific field (denoted by the <code>-v k=text</code>)?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 66
|
bash
|
# Parsing JSON with Unix tools
I'm trying to parse JSON returned from a curl request, like so:
```
curl 'http://twitter.com/users/username.json' |
sed -e 's/[{}]/''/g' |
awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
```
The above splits the JSON into fields, for example:
```
% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...
```
How do I print a specific field (denoted by the `-v k=text`)?
|
There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as [`jq`](https://stedolan.github.io/jq/):
```
curl -s 'https://api.github.com/users/lambda' | jq -r '.name'
```
You can also do this with tools that are likely already installed on your system, like Python using the [`json` module](https://docs.python.org/2/library/json.html), and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:
Python 3:
```
curl -s 'https://api.github.com/users/lambda' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"
```
Python 2:
```
export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
python2 -c "import sys, json; print json.load(sys.stdin)['name']"
```
## Frequently Asked Questions
### Why not a pure shell solution?
The standard [POSIX/Single Unix Specification shell](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html) is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are [somewhat hacky ways to do it](https://stackoverflow.com/questions/688849/associative-arrays-in-shell-scripts), but many of them can break if keys or values contain certain special characters.
Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.
Finally, writing a full fledged JSON parser in shell would be a significant enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.
### Why not use awk, sed, or grep?
It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.
However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.
So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on `jq` or Python.
I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.
## Historical notes
This answer originally recommended [jsawk](http://github.com/micha/jsawk), which should still work, but is a little more cumbersome to use than `jq`, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:
```
curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'
```
This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:
```
curl 'http://twitter.com/users/username.json' | jq -r '.text'
```
|
3811345
|
How to pass all arguments passed to my Bash script to a function of mine?
| 1,058
|
2010-09-28 09:24:16
|
<p>Let's say I have a function <code>abc()</code> that will handle the logic related to analyzing the arguments passed to my script.</p>
<p>How can I pass all arguments my Bash script has received to <code>abc()</code>? The number of arguments is variable, so I can't just hard-code the arguments passed like this:</p>
<pre><code>abc $1 $2 $3 $4
</code></pre>
<p>Better yet, is there any way for my function to have access to the script arguments' variables?</p>
| 654,094
| 130,758
|
2024-09-12 19:17:01
| 3,816,747
| 1,766
|
2010-09-28 20:24:18
| 89,817
|
2024-09-12 19:17:01
|
https://stackoverflow.com/q/3811345
|
https://stackoverflow.com/a/3816747
|
<p>The <code>$@</code> variable expands to all command-line parameters separated by spaces. Here is an example.</p>
<pre><code>abc "$@"
</code></pre>
<p>When using <code>$@</code>, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.</p>
<p>It is also worth noting that <code>$0</code> (generally the script's name or path) is not in <code>$@</code>.</p>
<p>The <a href="https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters" rel="noreferrer">Bash Reference Manual Special Parameters Section</a> says that <code>$@</code> expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is <code>"$@"</code> is equivalent to <code>"$1" "$2" "$3"...</code>.</p>
<h1>Passing <em>some</em> arguments:</h1>
<p>If you want to pass <em>all but the first</em> arguments, you can first use <code>shift</code> to "consume" the first argument and then pass <code>"$@"</code> to pass the remaining arguments to another command. In Bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: <code>"${@:3}"</code> will get you the arguments starting with <code>"$3"</code>. <code>"${@:3:4}"</code> will get you up to four arguments starting at <code>"$3"</code> (i.e. <code>"$3" "$4" "$5" "$6"</code>), if that many arguments were passed.</p>
<h1>Things you probably don't want to do:</h1>
<p><code>"$*"</code> gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of <code>$IFS</code> is). This loses the distinction between spaces <em>within</em> arguments and the spaces <em>between</em> arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. <code>echo "$*"</code>, provided you don't care about preserving the space within/between distinction.</p>
<p>Assigning the arguments to a regular variable (as in <code>args="$@"</code>) mashes all the arguments together like <code>"$*"</code> does. If you want to store the arguments in a variable, use an array with <code>args=("$@")</code> (the parentheses make it an array), and then reference them as e.g. <code>"${args[0]}"</code> etc. Note that in Bash and ksh, array indexes start at 0, so <code>$1</code> will be in <code>args[0]</code>, etc. zsh, on the other hand, starts array indexes at 1, so <code>$1</code> will be in <code>args[1]</code>. And more basic shells like dash don't have arrays at all.</p>
<p>Leaving off the double-quotes, with either <code>$@</code> or <code>$*</code>, will try to split each argument up into separate words (based on whitespace or whatever's in <code>$IFS</code>), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided. (Except in zsh, where this expansion doesn't take place by default.)</p>
|
<p>The <code>$@</code> variable expands to all command-line parameters separated by spaces. Here is an example.</p> <pre><code>abc "$@" </code></pre> <p>When using <code>$@</code>, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant she
|
387, 5569, 10355
|
bash, function, parameter-passing
|
<h1>How to pass all arguments passed to my Bash script to a function of mine?</h1>
<p>Let's say I have a function <code>abc()</code> that will handle the logic related to analyzing the arguments passed to my script.</p>
<p>How can I pass all arguments my Bash script has received to <code>abc()</code>? The number of arguments is variable, so I can't just hard-code the arguments passed like this:</p>
<pre><code>abc $1 $2 $3 $4
</code></pre>
<p>Better yet, is there any way for my function to have access to the script arguments' variables?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 67
|
bash
|
# How to pass all arguments passed to my Bash script to a function of mine?
Let's say I have a function `abc()` that will handle the logic related to analyzing the arguments passed to my script.
How can I pass all arguments my Bash script has received to `abc()`? The number of arguments is variable, so I can't just hard-code the arguments passed like this:
```
abc $1 $2 $3 $4
```
Better yet, is there any way for my function to have access to the script arguments' variables?
|
The `$@` variable expands to all command-line parameters separated by spaces. Here is an example.
```
abc "$@"
```
When using `$@`, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.
It is also worth noting that `$0` (generally the script's name or path) is not in `$@`.
The [Bash Reference Manual Special Parameters Section](https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters) says that `$@` expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is `"$@"` is equivalent to `"$1" "$2" "$3"...`.
# Passing *some* arguments:
If you want to pass *all but the first* arguments, you can first use `shift` to "consume" the first argument and then pass `"$@"` to pass the remaining arguments to another command. In Bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: `"${@:3}"` will get you the arguments starting with `"$3"`. `"${@:3:4}"` will get you up to four arguments starting at `"$3"` (i.e. `"$3" "$4" "$5" "$6"`), if that many arguments were passed.
# Things you probably don't want to do:
`"$*"` gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of `$IFS` is). This loses the distinction between spaces *within* arguments and the spaces *between* arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. `echo "$*"`, provided you don't care about preserving the space within/between distinction.
Assigning the arguments to a regular variable (as in `args="$@"`) mashes all the arguments together like `"$*"` does. If you want to store the arguments in a variable, use an array with `args=("$@")` (the parentheses make it an array), and then reference them as e.g. `"${args[0]}"` etc. Note that in Bash and ksh, array indexes start at 0, so `$1` will be in `args[0]`, etc. zsh, on the other hand, starts array indexes at 1, so `$1` will be in `args[1]`. And more basic shells like dash don't have arrays at all.
Leaving off the double-quotes, with either `$@` or `$*`, will try to split each argument up into separate words (based on whitespace or whatever's in `$IFS`), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided. (Except in zsh, where this expansion doesn't take place by default.)
|
3510673
|
Find and kill a process in one line using bash and regex
| 817
|
2010-08-18 09:33:41
|
<p>I often need to kill a process during programming.</p>
<p>The way I do it now is:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py'
user 5124 1.0 0.3 214588 13852 pts/4 Sl+ 11:19 0:00 python csp_build.py
user 5373 0.0 0.0 8096 960 pts/6 S+ 11:20 0:00 grep python csp_build.py
[~]$ kill 5124
</code></pre>
<p>How can I extract the process id automatically and kill it in the same line?</p>
<p>Like this:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>
</code></pre>
| 805,716
| 55,366
|
2024-07-04 15:28:11
| 3,510,850
| 1,745
|
2010-08-18 09:53:24
| 14,860
|
2023-02-08 21:13:28
|
https://stackoverflow.com/q/3510673
|
https://stackoverflow.com/a/3510850
|
<p>In <code>bash</code>, using only the basic tools listed in your question<sup>(1)</sup>, you should be able to do:</p>
<pre><code>kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')
</code></pre>
<p>Details on its workings are as follows:</p>
<ul>
<li>The <code>ps</code> gives you the list of all the processes.</li>
<li>The <code>grep</code> filters that based on your search string, <code>[p]</code> is a trick to stop you picking up the actual <code>grep</code> process itself.</li>
<li>The <code>awk</code> just gives you the second field of each line, which is the PID.</li>
<li>The <code>$(x)</code> construct means to execute <code>x</code> then take its output and put it on the command line. The output of that <code>ps</code> pipeline inside that construct above is the list of process IDs so you end up with a command like <code>kill 1234 1122 7654</code>.</li>
</ul>
<p>Here's a transcript showing it in action:</p>
<pre><code>pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+ Terminated sleep 3600
[1] Terminated sleep 3600
[2] Terminated sleep 3600
[3]- Terminated sleep 3600
[4]+ Terminated sleep 3600
</code></pre>
<p>and you can see it terminating all the sleepers.</p>
<p>Explaining the <code>grep '[p]ython csp_build.py'</code> bit in a bit more detail: when you do <code>sleep 3600 &</code> followed by <code>ps -ef | grep sleep</code>, you tend to get <em>two</em> processes with <code>sleep</code> in it, the <code>sleep 3600</code> and the <code>grep sleep</code> (because they both have <code>sleep</code> in them, that's not rocket science).</p>
<p>However, <code>ps -ef | grep '[s]leep'</code> won't create a <code>grep</code> process with <code>sleep</code> in it, it instead creates one with the command <code>grep '[s]leep'</code> and here's the tricky bit: the <code>grep</code> doesn't find that one, because it's looking for the regular expression "any character from the character class <code>[s]</code> (which is basically just <code>s</code>) followed by <code>leep</code>.</p>
<p>In other words, it's looking for <code>sleep</code> but the grep process is <code>grep '[s]leep'</code> which doesn't have the text <code>sleep</code> in it.</p>
<p>When I was shown this (by someone here on SO), I immediately started using it because</p>
<ul>
<li>it's one less process than adding <code>| grep -v grep</code>; and</li>
<li>it's elegant <em>and</em> sneaky, a rare combination :-)</li>
</ul>
<hr />
<p><sup>(1)</sup> If you're <em>not</em> limited to using those basic tools, there's a nifty <code>pgrep</code> command which will find processes based on certain criteria (assuming you have it available on your system, of course).</p>
<p>For example, you can use <code>pgrep sleep</code> to output the process IDs for all <code>sleep</code> commands (by default, it matches the process name). If you want to match the entire command line as shown in <code>ps</code>, you can do something like <code>pgrep -f 'sleep 9999'</code>.</p>
<p>As an aside, it doesn't list itself if you do <code>pgrep pgrep</code>, so the tricky filter method shown above is not necessary in this case.</p>
<p>You can <em>check</em> that the processes are the ones you're interested in by using <code>-a</code> to show the full process names. You can also limit the scope to your own processes (or a specific set of users) with <code>-u</code> or <code>-U</code>. See the <code>man</code> page for <code>pgrep</code>/<code>pkill</code> for more options.</p>
<p>Once you're satisfied it will only show the processes you're interested in, you can then use <code>pkill</code> with the same parameters to send a signal to all those processes.</p>
|
<p>In <code>bash</code>, using only the basic tools listed in your question<sup>(1)</sup>, you should be able to do:</p> <pre><code>kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}') </code></pre> <p>Details on its workings are as follows:</p> <ul> <li>The <code>ps</code> gives you the list of all the processes.</li> <li>The <code>grep</code> filters that based on your search string,
|
18, 387, 391, 990
|
awk, bash, regex, terminal
|
<h1>Find and kill a process in one line using bash and regex</h1>
<p>I often need to kill a process during programming.</p>
<p>The way I do it now is:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py'
user 5124 1.0 0.3 214588 13852 pts/4 Sl+ 11:19 0:00 python csp_build.py
user 5373 0.0 0.0 8096 960 pts/6 S+ 11:20 0:00 grep python csp_build.py
[~]$ kill 5124
</code></pre>
<p>How can I extract the process id automatically and kill it in the same line?</p>
<p>Like this:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 68
|
bash
|
# Find and kill a process in one line using bash and regex
I often need to kill a process during programming.
The way I do it now is:
```
[~]$ ps aux | grep 'python csp_build.py'
user 5124 1.0 0.3 214588 13852 pts/4 Sl+ 11:19 0:00 python csp_build.py
user 5373 0.0 0.0 8096 960 pts/6 S+ 11:20 0:00 grep python csp_build.py
[~]$ kill 5124
```
How can I extract the process id automatically and kill it in the same line?
Like this:
```
[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>
```
|
In `bash`, using only the basic tools listed in your question(1), you should be able to do:
```
kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')
```
Details on its workings are as follows:
- The `ps` gives you the list of all the processes.
- The `grep` filters that based on your search string, `[p]` is a trick to stop you picking up the actual `grep` process itself.
- The `awk` just gives you the second field of each line, which is the PID.
- The `$(x)` construct means to execute `x` then take its output and put it on the command line. The output of that `ps` pipeline inside that construct above is the list of process IDs so you end up with a command like `kill 1234 1122 7654`.
Here's a transcript showing it in action:
```
pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+ Terminated sleep 3600
[1] Terminated sleep 3600
[2] Terminated sleep 3600
[3]- Terminated sleep 3600
[4]+ Terminated sleep 3600
```
and you can see it terminating all the sleepers.
Explaining the `grep '[p]ython csp_build.py'` bit in a bit more detail: when you do `sleep 3600 &` followed by `ps -ef | grep sleep`, you tend to get *two* processes with `sleep` in it, the `sleep 3600` and the `grep sleep` (because they both have `sleep` in them, that's not rocket science).
However, `ps -ef | grep '[s]leep'` won't create a `grep` process with `sleep` in it, it instead creates one with the command `grep '[s]leep'` and here's the tricky bit: the `grep` doesn't find that one, because it's looking for the regular expression "any character from the character class `[s]` (which is basically just `s`) followed by `leep`.
In other words, it's looking for `sleep` but the grep process is `grep '[s]leep'` which doesn't have the text `sleep` in it.
When I was shown this (by someone here on SO), I immediately started using it because
- it's one less process than adding `| grep -v grep`; and
- it's elegant *and* sneaky, a rare combination :-)
---
(1) If you're *not* limited to using those basic tools, there's a nifty `pgrep` command which will find processes based on certain criteria (assuming you have it available on your system, of course).
For example, you can use `pgrep sleep` to output the process IDs for all `sleep` commands (by default, it matches the process name). If you want to match the entire command line as shown in `ps`, you can do something like `pgrep -f 'sleep 9999'`.
As an aside, it doesn't list itself if you do `pgrep pgrep`, so the tricky filter method shown above is not necessary in this case.
You can *check* that the processes are the ones you're interested in by using `-a` to show the full process names. You can also limit the scope to your own processes (or a specific set of users) with `-u` or `-U`. See the `man` page for `pgrep`/`pkill` for more options.
Once you're satisfied it will only show the processes you're interested in, you can then use `pkill` with the same parameters to send a signal to all those processes.
|
918886
|
How do I split a string on a delimiter in Bash?
| 3,033
|
2009-05-28 02:03:43
|
<p>I have this string stored in a variable:</p>
<pre><code>IN="bla@some.com;john@home.com"
</code></pre>
<p>Now I would like to split the strings by <code>;</code> delimiter so that I have:</p>
<pre><code>ADDR1="bla@some.com"
ADDR2="john@home.com"
</code></pre>
<p>I don't necessarily need the <code>ADDR1</code> and <code>ADDR2</code> variables. If they are elements of an array that's even better.</p>
<hr>
<p>After suggestions from the answers below, I ended up with the following which is what I was after:</p>
<pre><code>#!/usr/bin/env bash
IN="bla@some.com;john@home.com"
mails=$(echo $IN | tr ";" "\n")
for addr in $mails
do
echo "> [$addr]"
done
</code></pre>
<p>Output:</p>
<pre><code>> [bla@some.com]
> [john@home.com]
</code></pre>
<p>There was a solution involving setting <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">Internal_field_separator</a> (IFS) to <code>;</code>. I am not sure what happened with that answer, how do you reset <code>IFS</code> back to default?</p>
<p>RE: <code>IFS</code> solution, I tried this and it works, I keep the old <code>IFS</code> and then restore it:</p>
<pre><code>IN="bla@some.com;john@home.com"
OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
echo "> [$x]"
done
IFS=$OIFS
</code></pre>
<p>BTW, when I tried </p>
<pre><code>mails2=($IN)
</code></pre>
<p>I only got the first string when printing it in loop, without brackets around <code>$IN</code> it works.</p>
| 3,866,090
| 45,654
|
2025-03-21 10:32:51
| 918,931
| 1,733
|
2009-05-28 02:23:27
| 34,509
|
2021-03-09 17:42:51
|
https://stackoverflow.com/q/918886
|
https://stackoverflow.com/a/918931
|
<p>You can set the <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">internal field separator</a> (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to <code>IFS</code> only takes place to that single command's environment (to <code>read</code> ). It then parses the input according to the <code>IFS</code> variable value into an array, which we can then iterate over.</p>
<p>This example will parse one line of items separated by <code>;</code>, pushing it into an array:</p>
<pre><code>IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
# process "$i"
done
</code></pre>
<p>This other example is for processing the whole content of <code>$IN</code>, each time one line of input separated by <code>;</code>:</p>
<pre><code>while IFS=';' read -ra ADDR; do
for i in "${ADDR[@]}"; do
# process "$i"
done
done <<< "$IN"
</code></pre>
|
<p>You can set the <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">internal field separator</a> (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to <code>IFS</code> only takes place to that single command's environment (to <code>read</code> ). It then parses the input according to the <code>IFS</code> variable
|
387, 390, 531, 2193
|
bash, scripting, shell, split
|
<h1>How do I split a string on a delimiter in Bash?</h1>
<p>I have this string stored in a variable:</p>
<pre><code>IN="bla@some.com;john@home.com"
</code></pre>
<p>Now I would like to split the strings by <code>;</code> delimiter so that I have:</p>
<pre><code>ADDR1="bla@some.com"
ADDR2="john@home.com"
</code></pre>
<p>I don't necessarily need the <code>ADDR1</code> and <code>ADDR2</code> variables. If they are elements of an array that's even better.</p>
<hr>
<p>After suggestions from the answers below, I ended up with the following which is what I was after:</p>
<pre><code>#!/usr/bin/env bash
IN="bla@some.com;john@home.com"
mails=$(echo $IN | tr ";" "\n")
for addr in $mails
do
echo "> [$addr]"
done
</code></pre>
<p>Output:</p>
<pre><code>> [bla@some.com]
> [john@home.com]
</code></pre>
<p>There was a solution involving setting <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">Internal_field_separator</a> (IFS) to <code>;</code>. I am not sure what happened with that answer, how do you reset <code>IFS</code> back to default?</p>
<p>RE: <code>IFS</code> solution, I tried this and it works, I keep the old <code>IFS</code> and then restore it:</p>
<pre><code>IN="bla@some.com;john@home.com"
OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
echo "> [$x]"
done
IFS=$OIFS
</code></pre>
<p>BTW, when I tried </p>
<pre><code>mails2=($IN)
</code></pre>
<p>I only got the first string when printing it in loop, without brackets around <code>$IN</code> it works.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 69
|
bash
|
# How do I split a string on a delimiter in Bash?
I have this string stored in a variable:
```
IN="bla@some.com;john@home.com"
```
Now I would like to split the strings by `;` delimiter so that I have:
```
ADDR1="bla@some.com"
ADDR2="john@home.com"
```
I don't necessarily need the `ADDR1` and `ADDR2` variables. If they are elements of an array that's even better.
---
After suggestions from the answers below, I ended up with the following which is what I was after:
```
#!/usr/bin/env bash
IN="bla@some.com;john@home.com"
mails=$(echo $IN | tr ";" "\n")
for addr in $mails
do
echo "> [$addr]"
done
```
Output:
```
> [bla@some.com]
> [john@home.com]
```
There was a solution involving setting [Internal_field_separator](http://en.wikipedia.org/wiki/Internal_field_separator) (IFS) to `;`. I am not sure what happened with that answer, how do you reset `IFS` back to default?
RE: `IFS` solution, I tried this and it works, I keep the old `IFS` and then restore it:
```
IN="bla@some.com;john@home.com"
OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
echo "> [$x]"
done
IFS=$OIFS
```
BTW, when I tried
```
mails2=($IN)
```
I only got the first string when printing it in loop, without brackets around `$IN` it works.
|
You can set the [internal field separator](http://en.wikipedia.org/wiki/Internal_field_separator) (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to `IFS` only takes place to that single command's environment (to `read` ). It then parses the input according to the `IFS` variable value into an array, which we can then iterate over.
This example will parse one line of items separated by `;`, pushing it into an array:
```
IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
# process "$i"
done
```
This other example is for processing the whole content of `$IN`, each time one line of input separated by `;`:
```
while IFS=';' read -ra ADDR; do
for i in "${ADDR[@]}"; do
# process "$i"
done
done <<< "$IN"
```
|
53988638
|
Git fatal: protocol 'https' is not supported
| 586
|
2018-12-31 14:40:24
|
<p>I am going through Github's forking guide: <a href="https://guides.github.com/activities/forking/" rel="noreferrer">https://guides.github.com/activities/forking/</a>
and I am trying to clone the repository onto my computer. However, running the command:</p>
<pre><code>$ git clone https://github.com/./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
fatal: protocol 'https' is not supported
</code></pre>
<p>Also tried with SSH:</p>
<pre><code>$ git clone git@github.com:./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
Warning: Permanently added the RSA host key for IP address '.' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>Do I need to change some configuration setting on my computer or is this a problem with GitHub?</p>
<p>Edit: I have replaced my username and IP address with "." </p>
| 592,634
| 10,240,826
|
2024-10-18 04:51:26
| 55,985,462
| 1,728
|
2019-05-04 18:07:48
| 11,452,886
|
2024-02-02 06:29:03
|
https://stackoverflow.com/q/53988638
|
https://stackoverflow.com/a/55985462
|
<p>The problem is probably this:</p>
<ul>
<li>You tried to paste it using <kbd>CTRL</kbd> + <kbd>V</kbd> before and it didn't work,</li>
<li>so you went ahead and pasted it with classic <kbd>Right Click</kbd>.</li>
<li>Sadly, whenever you enter <kbd>CTRL</kbd> + <kbd>V</kbd> on <strong>terminal</strong> it adds a <strong>hidden</strong> <strong><kbd>^?</kbd></strong> (at least on my machine it is encoded like that) character that only appears after you <kbd>backspace</kbd> (go ahead and try it on git bash).</li>
</ul>
<p>So your link becomes <code>^?https://...</code> <strong>which is invalid</strong>.</p>
|
<p>The problem is probably this:</p> <ul> <li>You tried to paste it using <kbd>CTRL</kbd> + <kbd>V</kbd> before and it didn't work,</li> <li>so you went ahead and pasted it with classic <kbd>Right Click</kbd>.</li> <li>Sadly, whenever you enter <kbd>CTRL</kbd> + <kbd>V</kbd> on <strong>terminal</strong> it adds a <strong>hidden</strong> <strong><kbd>^?</kbd></strong> (at least on my machine it is
|
119, 61874
|
git, git-bash
|
<h1>Git fatal: protocol 'https' is not supported</h1>
<p>I am going through Github's forking guide: <a href="https://guides.github.com/activities/forking/" rel="noreferrer">https://guides.github.com/activities/forking/</a>
and I am trying to clone the repository onto my computer. However, running the command:</p>
<pre><code>$ git clone https://github.com/./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
fatal: protocol 'https' is not supported
</code></pre>
<p>Also tried with SSH:</p>
<pre><code>$ git clone git@github.com:./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
Warning: Permanently added the RSA host key for IP address '.' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>Do I need to change some configuration setting on my computer or is this a problem with GitHub?</p>
<p>Edit: I have replaced my username and IP address with "." </p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 70
|
bash
|
# Git fatal: protocol 'https' is not supported
I am going through Github's forking guide: <https://guides.github.com/activities/forking/>
and I am trying to clone the repository onto my computer. However, running the command:
```
$ git clone https://github.com/./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
fatal: protocol 'https' is not supported
```
Also tried with SSH:
```
$ git clone git@github.com:./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
Warning: Permanently added the RSA host key for IP address '.' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
Do I need to change some configuration setting on my computer or is this a problem with GitHub?
Edit: I have replaced my username and IP address with "."
|
The problem is probably this:
- You tried to paste it using `CTRL` + `V` before and it didn't work,
- so you went ahead and pasted it with classic `Right Click`.
- Sadly, whenever you enter `CTRL` + `V` on **terminal** it adds a **hidden** **`^?`** (at least on my machine it is encoded like that) character that only appears after you `backspace` (go ahead and try it on git bash).
So your link becomes `^?https://...` **which is invalid**.
|
19331497
|
Set environment variables from file of key/value pairs
| 1,232
|
2013-10-12 07:01:29
|
<p><strong>TL;DR:</strong> How do I export a set of key/value pairs from a text file into the shell environment?</p>
<hr />
<p>For the record, below is the original version of the question, with examples.</p>
<p>I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:</p>
<pre><code>MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
</code></pre>
<p>This file is stored in <code>./conf/prac1</code></p>
<p>My script <code>minientrega.sh</code> then parses the file using this code:</p>
<pre><code>cat ./conf/$1 | while read line; do
export $line
done
</code></pre>
<p>But when I execute <code>minientrega.sh prac1</code> in the command line it doesn't set the environment variables</p>
<p>I also tried using <code>source ./conf/$1</code> but the same problem still applies</p>
<p>Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.</p>
| 1,219,575
| 2,873,369
|
2025-10-23 11:17:37
| 20,909,045
| 1,727
|
2014-01-03 17:10:10
| 3,158,085
|
2022-07-24 06:51:24
|
https://stackoverflow.com/q/19331497
|
https://stackoverflow.com/a/20909045
|
<p>This might be helpful:</p>
<pre><code>export $(cat .env | xargs) && rails c
</code></pre>
<p>Reason why I use this is if I want to test <code>.env</code> stuff in my rails console.</p>
<p><a href="https://stackoverflow.com/users/293198/gabrielf">gabrielf</a> came up with a good way to keep the variables local. This solves the potential problem when going from project to project.</p>
<pre><code>env $(cat .env | xargs) rails
</code></pre>
<p>I've tested this with <code>bash 3.2.51(1)-release</code></p>
<hr />
<p><strong>Update:</strong></p>
<p>To ignore lines that start with <code>#</code>, use this (thanks to <a href="https://stackoverflow.com/questions/19331497/set-environment-variables-from-file#comment37343914_20909045">Pete's comment</a>):</p>
<pre><code>export $(grep -v '^#' .env | xargs)
</code></pre>
<p>And if you want to <code>unset</code> all of the variables defined in the file, use this:</p>
<pre><code>unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)
</code></pre>
<hr />
<p><strong>Update:</strong></p>
<p>To also handle values with spaces, use:</p>
<pre><code>export $(grep -v '^#' .env | xargs -d '\n')
</code></pre>
<p>on GNU systems -- or:</p>
<pre><code>export $(grep -v '^#' .env | xargs -0)
</code></pre>
<p>on BSD systems.</p>
<hr />
<p>From <a href="https://superuser.com/a/649780/139303">this answer</a> you can auto-detect the OS with this:</p>
<p><code>export-env.sh</code></p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
## Usage:
## . ./export-env.sh ; $COMMAND
## . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE}
unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then
export $(grep -v '^#' .env | xargs -d '\n')
elif [ "$unamestr" = 'FreeBSD' ] || [ "$unamestr" = 'Darwin' ]; then
export $(grep -v '^#' .env | xargs -0)
fi
</code></pre>
|
<p>This might be helpful:</p> <pre><code>export $(cat .env | xargs) && rails c </code></pre> <p>Reason why I use this is if I want to test <code>.env</code> stuff in my rails console.</p> <p><a href="https://stackoverflow.com/users/293198/gabrielf">gabrielf</a> came up with a good way to keep the variables local. This solves the potential problem when going from project to project.</p> <p
|
276, 387, 9013
|
bash, environment-variables, variables
|
<h1>Set environment variables from file of key/value pairs</h1>
<p><strong>TL;DR:</strong> How do I export a set of key/value pairs from a text file into the shell environment?</p>
<hr />
<p>For the record, below is the original version of the question, with examples.</p>
<p>I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:</p>
<pre><code>MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
</code></pre>
<p>This file is stored in <code>./conf/prac1</code></p>
<p>My script <code>minientrega.sh</code> then parses the file using this code:</p>
<pre><code>cat ./conf/$1 | while read line; do
export $line
done
</code></pre>
<p>But when I execute <code>minientrega.sh prac1</code> in the command line it doesn't set the environment variables</p>
<p>I also tried using <code>source ./conf/$1</code> but the same problem still applies</p>
<p>Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 71
|
bash
|
# Set environment variables from file of key/value pairs
**TL;DR:** How do I export a set of key/value pairs from a text file into the shell environment?
---
For the record, below is the original version of the question, with examples.
I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:
```
MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
```
This file is stored in `./conf/prac1`
My script `minientrega.sh` then parses the file using this code:
```
cat ./conf/$1 | while read line; do
export $line
done
```
But when I execute `minientrega.sh prac1` in the command line it doesn't set the environment variables
I also tried using `source ./conf/$1` but the same problem still applies
Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.
|
This might be helpful:
```
export $(cat .env | xargs) && rails c
```
Reason why I use this is if I want to test `.env` stuff in my rails console.
[gabrielf](https://stackoverflow.com/users/293198/gabrielf) came up with a good way to keep the variables local. This solves the potential problem when going from project to project.
```
env $(cat .env | xargs) rails
```
I've tested this with `bash 3.2.51(1)-release`
---
**Update:**
To ignore lines that start with `#`, use this (thanks to [Pete's comment](https://stackoverflow.com/questions/19331497/set-environment-variables-from-file#comment37343914_20909045)):
```
export $(grep -v '^#' .env | xargs)
```
And if you want to `unset` all of the variables defined in the file, use this:
```
unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)
```
---
**Update:**
To also handle values with spaces, use:
```
export $(grep -v '^#' .env | xargs -d '\n')
```
on GNU systems -- or:
```
export $(grep -v '^#' .env | xargs -0)
```
on BSD systems.
---
From [this answer](https://superuser.com/a/649780/139303) you can auto-detect the OS with this:
`export-env.sh`
```
#!/bin/sh
## Usage:
## . ./export-env.sh ; $COMMAND
## . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE}
unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then
export $(grep -v '^#' .env | xargs -d '\n')
elif [ "$unamestr" = 'FreeBSD' ] || [ "$unamestr" = 'Darwin' ]; then
export $(grep -v '^#' .env | xargs -0)
fi
```
|
6908143
|
Should I put #! (shebang) in Python scripts, and what form should it take?
| 1,291
|
2011-08-02 06:35:42
|
<p>Should I put the shebang in my Python scripts? In what form?</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python
</code></pre>
<p>or</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/local/bin/python
</code></pre>
<p>Are these equally portable? Which form is used most?</p>
<p><strong><em>Note:</em></strong> the <a href="https://github.com/facebook/tornado" rel="noreferrer">tornado</a> project uses the shebang. On the other hand the <a href="https://www.djangoproject.com/" rel="noreferrer">Django</a> project doesn't.</p>
| 959,425
| 1,206,051
|
2023-10-21 19:39:37
| 19,305,076
| 1,726
|
2013-10-10 19:58:55
| 144,020
|
2022-02-21 14:39:00
|
https://stackoverflow.com/q/6908143
|
https://stackoverflow.com/a/19305076
|
<p>The shebang line in any script determines the script's ability to be executed like a standalone executable without typing <code>python</code> beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use <em>is</em> important.</p>
<p><strong>Correct</strong> usage for (defaults to version 3.latest) <strong>Python 3</strong> scripts is:</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python3
</code></pre>
<p><strong>Correct</strong> usage for (defaults to version 2.latest) <strong>Python 2</strong> scripts is:</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python2
</code></pre>
<p>The following <strong>should <em>not</em> be used</strong> (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python
</code></pre>
<p>The reason for these recommendations, given in <a href="https://www.python.org/dev/peps/pep-0394/#recommendation" rel="noreferrer" title="PEP 394">PEP 394</a>, is that <code>python</code> can refer either to <code>python2</code> or <code>python3</code> on different systems.</p>
<p><strong>Also, do not use:</strong></p>
<pre class="lang-none prettyprint-override"><code>#!/usr/local/bin/python
</code></pre>
<blockquote>
<p>"python may be installed at /usr/bin/python or /bin/python in those
cases, the above #! will fail."</p>
</blockquote>
<p>―<a href="https://mail.python.org/pipermail/tutor/2007-June/054816.html" rel="noreferrer">"#!/usr/bin/env python" vs "#!/usr/local/bin/python"</a></p>
|
<p>The shebang line in any script determines the script's ability to be executed like a standalone executable without typing <code>python</code> beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which
|
16, 390, 8780, 60010
|
python, python-3.x, shebang, shell
|
<h1>Should I put #! (shebang) in Python scripts, and what form should it take?</h1>
<p>Should I put the shebang in my Python scripts? In what form?</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python
</code></pre>
<p>or</p>
<pre class="lang-none prettyprint-override"><code>#!/usr/local/bin/python
</code></pre>
<p>Are these equally portable? Which form is used most?</p>
<p><strong><em>Note:</em></strong> the <a href="https://github.com/facebook/tornado" rel="noreferrer">tornado</a> project uses the shebang. On the other hand the <a href="https://www.djangoproject.com/" rel="noreferrer">Django</a> project doesn't.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 72
|
bash
|
# Should I put #! (shebang) in Python scripts, and what form should it take?
Should I put the shebang in my Python scripts? In what form?
```
#!/usr/bin/env python
```
or
```
#!/usr/local/bin/python
```
Are these equally portable? Which form is used most?
***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djangoproject.com/) project doesn't.
|
The shebang line in any script determines the script's ability to be executed like a standalone executable without typing `python` beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use *is* important.
**Correct** usage for (defaults to version 3.latest) **Python 3** scripts is:
```
#!/usr/bin/env python3
```
**Correct** usage for (defaults to version 2.latest) **Python 2** scripts is:
```
#!/usr/bin/env python2
```
The following **should *not* be used** (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):
```
#!/usr/bin/env python
```
The reason for these recommendations, given in [PEP 394](https://www.python.org/dev/peps/pep-0394/#recommendation "PEP 394"), is that `python` can refer either to `python2` or `python3` on different systems.
**Also, do not use:**
```
#!/usr/local/bin/python
```
> "python may be installed at /usr/bin/python or /bin/python in those
> cases, the above #! will fail."
―["#!/usr/bin/env python" vs "#!/usr/local/bin/python"](https://mail.python.org/pipermail/tutor/2007-June/054816.html)
|
5163144
|
What are the special dollar sign shell variables?
| 971
|
2011-03-02 03:42:17
|
<p>In Bash, there appear to be several variables which hold special, consistently-meaning values. For instance,</p>
<pre><code>./myprogram &; echo $!
</code></pre>
<p>will return the <a href="https://en.wikipedia.org/wiki/Process_identifier" rel="noreferrer">PID</a> of the process which backgrounded <code>myprogram</code>. I know of others, such as <code>$?</code> which I think is the current TTY. Are there others?</p>
| 496,619
| 246,162
|
2022-12-19 19:51:52
| 5,163,260
| 1,707
|
2011-03-02 04:04:52
| 418,413
|
2022-12-19 19:49:42
|
https://stackoverflow.com/q/5163144
|
https://stackoverflow.com/a/5163260
|
<ul>
<li><code>$1</code>, <code>$2</code>, <code>$3</code>, ... are the <a href="https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html" rel="noreferrer">positional parameters</a>.</li>
<li><code>"$@"</code> is an array-like construct of all positional parameters, <code>{$1, $2, $3 ...}</code>.</li>
<li><code>"$*"</code> is the IFS expansion of all positional parameters, <code>$1 $2 $3 ...</code>.</li>
<li><code>$#</code> is the number of positional parameters.</li>
<li><code>$-</code> current options set for the shell.</li>
<li><code>$$</code> pid of the current shell (not subshell).</li>
<li><code>$_</code> most recent parameter (or the abs path of the command to start the current shell immediately after startup).</li>
<li><code>$IFS</code> is the (input) field separator.</li>
<li><code>$?</code> is the most recent foreground pipeline exit status.</li>
<li><code>$!</code> is the PID of the most recent background command.</li>
<li><code>$0</code> is the name of the shell or shell script.</li>
</ul>
<p>Most of the above can be found under <a href="https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html" rel="noreferrer">Special Parameters</a> in the Bash Reference Manual. <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Variables.html" rel="noreferrer">Here</a> are all the environment variables set by the shell.</p>
<p>For a comprehensive index, please see the <a href="https://www.gnu.org/software/bash/manual/html_node/Variable-Index.html" rel="noreferrer">Reference Manual Variable Index</a>.</p>
|
<ul> <li><code>$1</code>, <code>$2</code>, <code>$3</code>, ... are the <a href="https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html" rel="noreferrer">positional parameters</a>.</li> <li><code>"$@"</code> is an array-like construct of all positional parameters, <code>{$1, $2, $3 ...}</code>.</li> <li><code>"$*"</code> is the IFS expansion of all positi
|
387, 9013, 29953
|
bash, dollar-sign, environment-variables
|
<h1>What are the special dollar sign shell variables?</h1>
<p>In Bash, there appear to be several variables which hold special, consistently-meaning values. For instance,</p>
<pre><code>./myprogram &; echo $!
</code></pre>
<p>will return the <a href="https://en.wikipedia.org/wiki/Process_identifier" rel="noreferrer">PID</a> of the process which backgrounded <code>myprogram</code>. I know of others, such as <code>$?</code> which I think is the current TTY. Are there others?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 73
|
bash
|
# What are the special dollar sign shell variables?
In Bash, there appear to be several variables which hold special, consistently-meaning values. For instance,
```
./myprogram &; echo $!
```
will return the [PID](https://en.wikipedia.org/wiki/Process_identifier) of the process which backgrounded `myprogram`. I know of others, such as `$?` which I think is the current TTY. Are there others?
|
- `$1`, `$2`, `$3`, ... are the [positional parameters](https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html).
- `"$@"` is an array-like construct of all positional parameters, `{$1, $2, $3 ...}`.
- `"$*"` is the IFS expansion of all positional parameters, `$1 $2 $3 ...`.
- `$#` is the number of positional parameters.
- `$-` current options set for the shell.
- `$$` pid of the current shell (not subshell).
- `$_` most recent parameter (or the abs path of the command to start the current shell immediately after startup).
- `$IFS` is the (input) field separator.
- `$?` is the most recent foreground pipeline exit status.
- `$!` is the PID of the most recent background command.
- `$0` is the name of the shell or shell script.
Most of the above can be found under [Special Parameters](https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html) in the Bash Reference Manual. [Here](https://www.gnu.org/software/bash/manual/html_node/Shell-Variables.html) are all the environment variables set by the shell.
For a comprehensive index, please see the [Reference Manual Variable Index](https://www.gnu.org/software/bash/manual/html_node/Variable-Index.html).
|
1092631
|
How to get the current time in seconds since the epoch, in Bash on Linux?
| 937
|
2009-07-07 14:22:31
|
<p>I need something simple like <code>date</code>, but in seconds since 1970 instead of the current date, hours, minutes, and seconds.</p>
<p><code>date</code> doesn't seem to offer that option. Is there an easy way?</p>
| 901,984
| 23,420
|
2025-02-03 15:49:25
| 1,092,643
| 1,696
|
2009-07-07 14:25:00
| 71,347
|
2023-04-11 00:19:40
|
https://stackoverflow.com/q/1092631
|
https://stackoverflow.com/a/1092643
|
<p>This should work:</p>
<pre><code>date +%s
</code></pre>
<p>As recently corrected in the <a href="https://man7.org/linux/man-pages/man1/date.1.html" rel="noreferrer">date manual</a>:</p>
<blockquote>
<p>%s = seconds since the Epoch (1970-01-01 00:00 UTC)</p>
</blockquote>
|
<p>This should work:</p> <pre><code>date +%s </code></pre> <p>As recently corrected in the <a href="https://man7.org/linux/man-pages/man1/date.1.html" rel="noreferrer">date manual</a>:</p> <blockquote> <p>%s = seconds since the Epoch (1970-01-01 00:00 UTC)</p> </blockquote>
|
58, 387, 1263, 2177, 32842
|
bash, datetime, linux, timestamp, unix-timestamp
|
<h1>How to get the current time in seconds since the epoch, in Bash on Linux?</h1>
<p>I need something simple like <code>date</code>, but in seconds since 1970 instead of the current date, hours, minutes, and seconds.</p>
<p><code>date</code> doesn't seem to offer that option. Is there an easy way?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 74
|
bash
|
# How to get the current time in seconds since the epoch, in Bash on Linux?
I need something simple like `date`, but in seconds since 1970 instead of the current date, hours, minutes, and seconds.
`date` doesn't seem to offer that option. Is there an easy way?
|
This should work:
```
date +%s
```
As recently corrected in the [date manual](https://man7.org/linux/man-pages/man1/date.1.html):
> %s = seconds since the Epoch (1970-01-01 00:00 UTC)
|
1289026
|
Syntax for a single-line while loop in Bash
| 906
|
2009-08-17 16:31:47
|
<p>I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:</p>
<pre><code>while [ 1 ]
do
foo
sleep 2
done
</code></pre>
| 1,148,002
| 409
|
2023-04-30 16:51:11
| 1,289,029
| 1,693
|
2009-08-17 16:32:32
| 78,374
|
2009-08-17 16:32:32
|
https://stackoverflow.com/q/1289026
|
https://stackoverflow.com/a/1289029
|
<pre><code>while true; do foo; sleep 2; done
</code></pre>
<p>By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.</p>
<pre><code>$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do echo "hello"; sleep 2; done
</code></pre>
|
<pre><code>while true; do foo; sleep 2; done </code></pre> <p>By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.</p> <pre><code>$ while true > do > echo "hello" > sleep 2 > done hello hello hello ^C $ <arrow up> while true; do echo "hello";
|
387, 2314, 17310
|
bash, loops, while-loop
|
<h1>Syntax for a single-line while loop in Bash</h1>
<p>I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:</p>
<pre><code>while [ 1 ]
do
foo
sleep 2
done
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 75
|
bash
|
# Syntax for a single-line while loop in Bash
I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:
```
while [ 1 ]
do
foo
sleep 2
done
```
|
```
while true; do foo; sleep 2; done
```
By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.
```
$ while true
> do
> echo "hello"
> sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do echo "hello"; sleep 2; done
```
|
450799
|
Shell command to sum integers, one per line?
| 1,131
|
2009-01-16 15:42:03
|
<p>I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.</p>
<p>As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of <code>sed</code> reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used <code>expr</code> in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).</p>
<p>How can I get the summation of integers?</p>
| 806,368
| 45,664
|
2025-12-19 16:10:30
| 450,821
| 1,689
|
2009-01-16 15:46:00
| 6,521
|
2016-10-13 04:21:53
|
https://stackoverflow.com/q/450799
|
https://stackoverflow.com/a/450821
|
<p>Bit of awk should do it? </p>
<pre><code>awk '{s+=$1} END {print s}' mydatafile
</code></pre>
<p>Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use <code>printf</code> rather than <code>print</code>:</p>
<pre><code>awk '{s+=$1} END {printf "%.0f", s}' mydatafile
</code></pre>
|
<p>Bit of awk should do it? </p> <pre><code>awk '{s+=$1} END {print s}' mydatafile </code></pre> <p>Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use <code>printf</code> rather than <code>print</code>:</p> <pre><code>awk '{s+=$1} END {printf "%.0f", s}' mydatafile </c
|
390
|
shell
|
<h1>Shell command to sum integers, one per line?</h1>
<p>I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.</p>
<p>As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of <code>sed</code> reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used <code>expr</code> in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).</p>
<p>How can I get the summation of integers?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 76
|
bash
|
# Shell command to sum integers, one per line?
I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.
As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of `sed` reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used `expr` in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).
How can I get the summation of integers?
|
Bit of awk should do it?
```
awk '{s+=$1} END {print s}' mydatafile
```
Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use `printf` rather than `print`:
```
awk '{s+=$1} END {printf "%.0f", s}' mydatafile
```
|
4822471
|
Count number of lines in a git repository
| 1,101
|
2011-01-27 22:07:06
|
<p>How would I count the total number of lines present in all the files in a git repository?</p>
<p><code>git ls-files</code> gives me a list of files tracked by git.</p>
<p>I'm looking for a command to <code>cat</code> all those files. Something like</p>
<pre><code>git ls-files | [cat all these files] | wc -l
</code></pre>
| 689,828
| 320,615
|
2025-09-09 15:19:41
| 4,822,516
| 1,670
|
2011-01-27 22:11:03
| 116,908
|
2021-08-01 20:33:32
|
https://stackoverflow.com/q/4822471
|
https://stackoverflow.com/a/4822516
|
<p><code>xargs</code> will let you <code>cat</code> all the files together before passing them to <code>wc</code>, like you asked:</p>
<pre><code>git ls-files | xargs cat | wc -l
</code></pre>
<p>But skipping the intermediate <code>cat</code> gives you more information and is probably better:</p>
<pre><code>git ls-files | xargs wc -l
</code></pre>
|
<p><code>xargs</code> will let you <code>cat</code> all the files together before passing them to <code>wc</code>, like you asked:</p> <pre><code>git ls-files | xargs cat | wc -l </code></pre> <p>But skipping the intermediate <code>cat</code> gives you more information and is probably better:</p> <pre><code>git ls-files | xargs wc -l </code></pre>
|
119, 387, 390, 29837
|
bash, git, line-count, shell
|
<h1>Count number of lines in a git repository</h1>
<p>How would I count the total number of lines present in all the files in a git repository?</p>
<p><code>git ls-files</code> gives me a list of files tracked by git.</p>
<p>I'm looking for a command to <code>cat</code> all those files. Something like</p>
<pre><code>git ls-files | [cat all these files] | wc -l
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 77
|
bash
|
# Count number of lines in a git repository
How would I count the total number of lines present in all the files in a git repository?
`git ls-files` gives me a list of files tracked by git.
I'm looking for a command to `cat` all those files. Something like
```
git ls-files | [cat all these files] | wc -l
```
|
`xargs` will let you `cat` all the files together before passing them to `wc`, like you asked:
```
git ls-files | xargs cat | wc -l
```
But skipping the intermediate `cat` gives you more information and is probably better:
```
git ls-files | xargs wc -l
```
|
2172352
|
In Bash, how can I check if a string begins with some value?
| 1,230
|
2010-01-31 16:12:46
|
<p>I would like to check if a string begins with "node" e.g. "node001". Something like</p>
<pre><code>if [ $HOST == node* ]
then
echo yes
fi
</code></pre>
<p>How can I do it correctly?</p>
<hr />
<p>I further need to combine expressions to check if <code>HOST</code> is either "user1" or begins with "node":</p>
<pre><code>if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi
> > > -bash: [: too many arguments
</code></pre>
<p>How can I do it correctly?</p>
| 1,115,459
| 156,458
|
2025-02-07 20:22:52
| 2,172,367
| 1,621
|
2010-01-31 16:16:02
| 126,042
|
2017-09-26 10:17:11
|
https://stackoverflow.com/q/2172352
|
https://stackoverflow.com/a/2172367
|
<p>This snippet on the <a href="http://tldp.org/LDP/abs/html/comparison-ops.html" rel="noreferrer">Advanced Bash Scripting Guide</a> says:</p>
<pre><code># The == comparison operator behaves differently within a double-brackets
# test than within single brackets.
[[ $a == z* ]] # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
</code></pre>
<p>So you had it <em>nearly</em> correct; you needed <em>double</em> brackets, not single brackets.</p>
<hr>
<p>With regards to your second question, you can write it this way:</p>
<pre><code>HOST=user1
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes1
fi
HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes2
fi
</code></pre>
<p>Which will echo</p>
<pre><code>yes1
yes2
</code></pre>
<p>Bash's <code>if</code> syntax is hard to get used to (IMO).</p>
|
<p>This snippet on the <a href="http://tldp.org/LDP/abs/html/comparison-ops.html" rel="noreferrer">Advanced Bash Scripting Guide</a> says:</p> <pre><code># The == comparison operator behaves differently within a double-brackets # test than within single brackets. [[ $a == z* ]] # True if $a starts with a "z" (wildcard matching). [[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
|
139, 387, 588
|
bash, comparison, string
|
<h1>In Bash, how can I check if a string begins with some value?</h1>
<p>I would like to check if a string begins with "node" e.g. "node001". Something like</p>
<pre><code>if [ $HOST == node* ]
then
echo yes
fi
</code></pre>
<p>How can I do it correctly?</p>
<hr />
<p>I further need to combine expressions to check if <code>HOST</code> is either "user1" or begins with "node":</p>
<pre><code>if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi
> > > -bash: [: too many arguments
</code></pre>
<p>How can I do it correctly?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 78
|
bash
|
# In Bash, how can I check if a string begins with some value?
I would like to check if a string begins with "node" e.g. "node001". Something like
```
if [ $HOST == node* ]
then
echo yes
fi
```
How can I do it correctly?
---
I further need to combine expressions to check if `HOST` is either "user1" or begins with "node":
```
if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi
> > > -bash: [: too many arguments
```
How can I do it correctly?
|
This snippet on the [Advanced Bash Scripting Guide](http://tldp.org/LDP/abs/html/comparison-ops.html) says:
```
# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.
[[ $a == z* ]] # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
```
So you had it *nearly* correct; you needed *double* brackets, not single brackets.
---
With regards to your second question, you can write it this way:
```
HOST=user1
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes1
fi
HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
echo yes2
fi
```
Which will echo
```
yes1
yes2
```
Bash's `if` syntax is hard to get used to (IMO).
|
2342826
|
How can I pipe stderr, and not stdout?
| 1,319
|
2010-02-26 15:53:27
|
<p>I have a program that writes information to <code>stdout</code> and <code>stderr</code>, and I need to process the <code>stderr</code> with <code>grep</code>, leaving <code>stdout</code> aside.</p>
<p>Using a temporary file, one could do it in two steps:</p>
<pre><code>command > /dev/null 2> temp.file
grep 'something' temp.file
</code></pre>
<p>But how can this be achieved without temp files, using one command and pipes?</p>
| 651,361
| null |
2024-02-04 11:40:35
| 2,342,841
| 1,606
|
2010-02-26 15:55:18
| 15,168
|
2020-10-15 07:40:38
|
https://stackoverflow.com/q/2342826
|
https://stackoverflow.com/a/2342841
|
<p>First redirect stderr to stdout — the pipe; then redirect stdout to <code>/dev/null</code> (without changing where stderr is going):</p>
<pre><code>command 2>&1 >/dev/null | grep 'something'
</code></pre>
<p>For the details of I/O redirection in all its variety, see the chapter on <a href="http://www.gnu.org/software/bash/manual/bash.html#Redirections" rel="noreferrer">Redirections</a> in the Bash reference manual.</p>
<p>Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation <code>2>&1</code> makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html" rel="noreferrer"><code>dup2()</code></a> and <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html" rel="noreferrer"><code>open()</code></a>). The operation <code>>/dev/null</code> then changes file descriptor 1 so that it refers to an open file description for <code>/dev/null</code>, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.</p>
|
<p>First redirect stderr to stdout — the pipe; then redirect stdout to <code>/dev/null</code> (without changing where stderr is going):</p> <pre><code>command 2>&1 >/dev/null | grep 'something' </code></pre> <p>For the details of I/O redirection in all its variety, see the chapter on <a href="http://www.gnu.org/software/bash/manual/bash.html#Redirections" rel="noreferrer">Redirections</a
|
387, 1271, 4867, 5813, 19156
|
bash, grep, pipe, stderr, stdout
|
<h1>How can I pipe stderr, and not stdout?</h1>
<p>I have a program that writes information to <code>stdout</code> and <code>stderr</code>, and I need to process the <code>stderr</code> with <code>grep</code>, leaving <code>stdout</code> aside.</p>
<p>Using a temporary file, one could do it in two steps:</p>
<pre><code>command > /dev/null 2> temp.file
grep 'something' temp.file
</code></pre>
<p>But how can this be achieved without temp files, using one command and pipes?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 79
|
bash
|
# How can I pipe stderr, and not stdout?
I have a program that writes information to `stdout` and `stderr`, and I need to process the `stderr` with `grep`, leaving `stdout` aside.
Using a temporary file, one could do it in two steps:
```
command > /dev/null 2> temp.file
grep 'something' temp.file
```
But how can this be achieved without temp files, using one command and pipes?
|
First redirect stderr to stdout — the pipe; then redirect stdout to `/dev/null` (without changing where stderr is going):
```
command 2>&1 >/dev/null | grep 'something'
```
For the details of I/O redirection in all its variety, see the chapter on [Redirections](http://www.gnu.org/software/bash/manual/bash.html#Redirections) in the Bash reference manual.
Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation `2>&1` makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see [`dup2()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html) and [`open()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)). The operation `>/dev/null` then changes file descriptor 1 so that it refers to an open file description for `/dev/null`, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.
|
625409
|
How do I put an already-running process under nohup?
| 1,127
|
2009-03-09 08:33:37
|
<p>I have a process that is already running for a long time and don't want to end it.</p>
<p>How do I put it under nohup (that is, how do I cause it to continue running even if I close the terminal?)</p>
| 563,545
| 63,051
|
2025-08-11 15:46:35
| 625,436
| 1,606
|
2009-03-09 08:41:58
| 7,190
|
2014-05-21 00:19:14
|
https://stackoverflow.com/q/625409
|
https://stackoverflow.com/a/625436
|
<p>Using the <a href="http://web.mit.edu/gnu/doc/html/features_5.html" rel="noreferrer">Job Control</a> of bash to send the process into the background:</p>
<ol>
<li><kbd>Ctrl</kbd>+<kbd>Z</kbd> to stop (pause) the program and get back to the shell.</li>
<li><code>bg</code> to run it in the background.</li>
<li><code>disown -h [job-spec]</code> where [job-spec] is the job number (like <code>%1</code> for the first running job; find about your number with the <code>jobs</code> command) so that the job isn't killed when the terminal closes.</li>
</ol>
|
<p>Using the <a href="http://web.mit.edu/gnu/doc/html/features_5.html" rel="noreferrer">Job Control</a> of bash to send the process into the background:</p> <ol> <li><kbd>Ctrl</kbd>+<kbd>Z</kbd> to stop (pause) the program and get back to the shell.</li> <li><code>bg</code> to run it in the background.</li> <li><code>disown -h [job-spec]</code> where [job-spec] is the job number (like <code>%1</c
|
387, 390, 18966, 35582, 55914
|
bash, interruption, job-scheduling, nohup, shell
|
<h1>How do I put an already-running process under nohup?</h1>
<p>I have a process that is already running for a long time and don't want to end it.</p>
<p>How do I put it under nohup (that is, how do I cause it to continue running even if I close the terminal?)</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 80
|
bash
|
# How do I put an already-running process under nohup?
I have a process that is already running for a long time and don't want to end it.
How do I put it under nohup (that is, how do I cause it to continue running even if I close the terminal?)
|
Using the [Job Control](http://web.mit.edu/gnu/doc/html/features_5.html) of bash to send the process into the background:
1. `Ctrl`+`Z` to stop (pause) the program and get back to the shell.
2. `bg` to run it in the background.
3. `disown -h [job-spec]` where [job-spec] is the job number (like `%1` for the first running job; find about your number with the `jobs` command) so that the job isn't killed when the terminal closes.
|
82256
|
How do I use sudo to redirect output to a location I don't have permission to write to?
| 1,152
|
2008-09-17 11:44:39
|
<p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p>
<p>The trouble is, this contrived example doesn't work:</p>
<pre><code>sudo ls -hal /root/ > /root/test.out
</code></pre>
<p>I just receive the response:</p>
<pre><code>-bash: /root/test.out: Permission denied
</code></pre>
<p>How can I get this to work?</p>
| 366,608
| 6,910
|
2021-12-06 06:21:44
| 82,278
| 1,592
|
2008-09-17 11:48:56
| 12,892
|
2015-09-09 20:16:26
|
https://stackoverflow.com/q/82256
|
https://stackoverflow.com/a/82278
|
<p>Your command does not work because the redirection is performed by your shell which does not have the permission to write to <code>/root/test.out</code>. The redirection of the output <strong>is not</strong> performed by sudo.</p>
<p>There are multiple solutions:</p>
<ul>
<li><p>Run a shell with sudo and give the command to it by using the <code>-c</code> option:</p>
<pre><code>sudo sh -c 'ls -hal /root/ > /root/test.out'
</code></pre></li>
<li><p>Create a script with your commands and run that script with sudo:</p>
<pre><code>#!/bin/sh
ls -hal /root/ > /root/test.out
</code></pre>
<p>Run <code>sudo ls.sh</code>. See Steve Bennett's <a href="https://stackoverflow.com/a/16514624/12892">answer</a> if you don't want to create a temporary file.</p></li>
<li><p>Launch a shell with <code>sudo -s</code> then run your commands:</p>
<pre><code>[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
</code></pre></li>
<li><p>Use <code>sudo tee</code> (if you have to escape a lot when using the <code>-c</code> option):</p>
<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
</code></pre>
<p>The redirect to <code>/dev/null</code> is needed to stop <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html" rel="noreferrer"><strong>tee</strong></a> from outputting to the screen. To <em>append</em> instead of overwriting the output file
(<code>>></code>), use <code>tee -a</code> or <code>tee --append</code> (the last one is specific to <a href="https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer">GNU coreutils</a>).</p></li>
</ul>
<p>Thanks go to <a href="https://stackoverflow.com/a/82274/12892">Jd</a>, <a href="https://stackoverflow.com/a/82279/12892">Adam J. Forster</a> and <a href="https://stackoverflow.com/a/82553/12892">Johnathan</a> for the second, third and fourth solutions.</p>
|
<p>Your command does not work because the redirection is performed by your shell which does not have the permission to write to <code>/root/test.out</code>. The redirection of the output <strong>is not</strong> performed by sudo.</p> <p>There are multiple solutions:</p> <ul> <li><p>Run a shell with sudo and give the command to it by using the <code>-c</code> option:</p> <pre><code>sudo sh -c 'l
|
58, 359, 387, 1674, 26698
|
bash, io-redirection, linux, permissions, sudo
|
<h1>How do I use sudo to redirect output to a location I don't have permission to write to?</h1>
<p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p>
<p>The trouble is, this contrived example doesn't work:</p>
<pre><code>sudo ls -hal /root/ > /root/test.out
</code></pre>
<p>I just receive the response:</p>
<pre><code>-bash: /root/test.out: Permission denied
</code></pre>
<p>How can I get this to work?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 81
|
bash
|
# How do I use sudo to redirect output to a location I don't have permission to write to?
I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.
The trouble is, this contrived example doesn't work:
```
sudo ls -hal /root/ > /root/test.out
```
I just receive the response:
```
-bash: /root/test.out: Permission denied
```
How can I get this to work?
|
Your command does not work because the redirection is performed by your shell which does not have the permission to write to `/root/test.out`. The redirection of the output **is not** performed by sudo.
There are multiple solutions:
- Run a shell with sudo and give the command to it by using the `-c` option:
```
sudo sh -c 'ls -hal /root/ > /root/test.out'
```
- Create a script with your commands and run that script with sudo:
```
#!/bin/sh
ls -hal /root/ > /root/test.out
```
Run `sudo ls.sh`. See Steve Bennett's [answer](https://stackoverflow.com/a/16514624/12892) if you don't want to create a temporary file.
- Launch a shell with `sudo -s` then run your commands:
```
[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
```
- Use `sudo tee` (if you have to escape a lot when using the `-c` option):
```
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
```
The redirect to `/dev/null` is needed to stop [**tee**](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html) from outputting to the screen. To *append* instead of overwriting the output file
(`>>`), use `tee -a` or `tee --append` (the last one is specific to [GNU coreutils](https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html)).
Thanks go to [Jd](https://stackoverflow.com/a/82274/12892), [Adam J. Forster](https://stackoverflow.com/a/82279/12892) and [Johnathan](https://stackoverflow.com/a/82553/12892) for the second, third and fourth solutions.
|
7427262
|
How to read a file into a variable in shell?
| 782
|
2011-09-15 07:29:16
|
<p>I want to read a file and save it in variable, but I need to keep the variable and not just print out the file.
How can I do this? I have written this script but it isn't quite what I needed:</p>
<pre><code>#!/bin/sh
while read LINE
do
echo $LINE
done <$1
echo 11111-----------
echo $LINE
</code></pre>
<p>In my script, I can give the file name as a parameter, so, if the file contains "aaaa", for example, it would print out this:</p>
<pre><code>aaaa
11111-----
</code></pre>
<p>But this just prints out the file onto the screen, and I want to save it into a variable!
Is there an easy way to do this?</p>
| 1,453,203
| 405,514
|
2025-12-16 19:33:13
| 10,771,857
| 1,574
|
2012-05-27 05:22:04
| 90,123
|
2025-12-16 19:33:13
|
https://stackoverflow.com/q/7427262
|
https://stackoverflow.com/a/10771857
|
<p>In cross-platform, lowest-common-denominator <code>sh</code> you use:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
value=$(cat config.txt)
echo "$value"
</code></pre>
<p>In <code>bash</code> or <code>zsh</code>, to read a whole file into a variable without invoking <code>cat</code>:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
value=$(<config.txt)
echo "$value"
</code></pre>
<p>Invoking <code>cat</code> in <code>bash</code> or <code>zsh</code> to slurp a file would be considered a <a href="https://web.archive.org/web/20160711205930/http://porkmail.org/era/unix/award.html" rel="nofollow noreferrer">Useless Use of Cat</a>.</p>
<p>Note that it is not necessary to quote the command substitution to preserve newlines.</p>
<p>See: <a href="https://web.archive.org/web/20120606001330/http://wiki.bash-hackers.org/syntax/expansion/cmdsubst" rel="nofollow noreferrer">Bash Hacker's Wiki - Command substitution - Specialities</a>.</p>
|
<p>In cross-platform, lowest-common-denominator <code>sh</code> you use:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/sh value=$(cat config.txt) echo "$value" </code></pre> <p>In <code>bash</code> or <code>zsh</code>, to read a whole file into a variable without invoking <code>cat</code>:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash value=$(<config
|
34, 390, 10327
|
sh, shell, unix
|
<h1>How to read a file into a variable in shell?</h1>
<p>I want to read a file and save it in variable, but I need to keep the variable and not just print out the file.
How can I do this? I have written this script but it isn't quite what I needed:</p>
<pre><code>#!/bin/sh
while read LINE
do
echo $LINE
done <$1
echo 11111-----------
echo $LINE
</code></pre>
<p>In my script, I can give the file name as a parameter, so, if the file contains "aaaa", for example, it would print out this:</p>
<pre><code>aaaa
11111-----
</code></pre>
<p>But this just prints out the file onto the screen, and I want to save it into a variable!
Is there an easy way to do this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 82
|
bash
|
# How to read a file into a variable in shell?
I want to read a file and save it in variable, but I need to keep the variable and not just print out the file.
How can I do this? I have written this script but it isn't quite what I needed:
```
#!/bin/sh
while read LINE
do
echo $LINE
done <$1
echo 11111-----------
echo $LINE
```
In my script, I can give the file name as a parameter, so, if the file contains "aaaa", for example, it would print out this:
```
aaaa
11111-----
```
But this just prints out the file onto the screen, and I want to save it into a variable!
Is there an easy way to do this?
|
In cross-platform, lowest-common-denominator `sh` you use:
```
#!/bin/sh
value=$(cat config.txt)
echo "$value"
```
In `bash` or `zsh`, to read a whole file into a variable without invoking `cat`:
```
#!/bin/bash
value=$(<config.txt)
echo "$value"
```
Invoking `cat` in `bash` or `zsh` to slurp a file would be considered a [Useless Use of Cat](https://web.archive.org/web/20160711205930/http://porkmail.org/era/unix/award.html).
Note that it is not necessary to quote the command substitution to preserve newlines.
See: [Bash Hacker's Wiki - Command substitution - Specialities](https://web.archive.org/web/20120606001330/http://wiki.bash-hackers.org/syntax/expansion/cmdsubst).
|
7161821
|
How to 'grep' a continuous stream?
| 890
|
2011-08-23 13:34:31
|
<p>Is that possible to use <code>grep</code> on a continuous stream?</p>
<p>What I mean is sort of a <code>tail -f <file></code> command, but with <code>grep</code> on the output in order to keep only the lines that interest me.</p>
<p>I've tried <code>tail -f <file> | grep pattern</code> but it seems that <code>grep</code> can only be executed once <code>tail</code> finishes, that is to say never.</p>
| 454,662
| 245,552
|
2025-06-11 12:59:55
| 7,162,898
| 1,558
|
2011-08-23 14:44:59
| 907,949
|
2020-11-30 13:23:37
|
https://stackoverflow.com/q/7161821
|
https://stackoverflow.com/a/7162898
|
<p>Turn on <code>grep</code>'s line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)</p>
<pre><code>tail -f file | grep --line-buffered my_pattern
</code></pre>
<p>It looks like a while ago <code>--line-buffered</code> didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, <code>--line-buffered</code> is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).</p>
|
<p>Turn on <code>grep</code>'s line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)</p> <pre><code>tail -f file | grep --line-buffered my_pattern </code></pre> <p>It looks like a while ago <code>--line-buffered</code> didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020,
|
58, 387, 390, 1271, 7896
|
bash, grep, linux, shell, tail
|
<h1>How to 'grep' a continuous stream?</h1>
<p>Is that possible to use <code>grep</code> on a continuous stream?</p>
<p>What I mean is sort of a <code>tail -f <file></code> command, but with <code>grep</code> on the output in order to keep only the lines that interest me.</p>
<p>I've tried <code>tail -f <file> | grep pattern</code> but it seems that <code>grep</code> can only be executed once <code>tail</code> finishes, that is to say never.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 83
|
bash
|
# How to 'grep' a continuous stream?
Is that possible to use `grep` on a continuous stream?
What I mean is sort of a `tail -f <file>` command, but with `grep` on the output in order to keep only the lines that interest me.
I've tried `tail -f <file> | grep pattern` but it seems that `grep` can only be executed once `tail` finishes, that is to say never.
|
Turn on `grep`'s line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)
```
tail -f file | grep --line-buffered my_pattern
```
It looks like a while ago `--line-buffered` didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, `--line-buffered` is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).
|
18568706
|
Check number of arguments passed to a Bash script
| 1,028
|
2013-09-02 08:28:51
|
<p>I would like my Bash script to print an error message if the required argument count is not met.</p>
<p>I tried the following code:</p>
<pre><code>#!/bin/bash
echo Script name: $0
echo $# arguments
if [$# -ne 1];
then echo "illegal number of parameters"
fi
</code></pre>
<p>For some unknown reason I've got the following error:</p>
<pre><code>test: line 4: [2: command not found
</code></pre>
<p>What am I doing wrong?</p>
| 1,242,762
| 1,337,871
|
2023-03-23 20:35:25
| 18,568,726
| 1,557
|
2013-09-02 08:30:04
| 445,221
|
2021-09-23 00:29:06
|
https://stackoverflow.com/q/18568706
|
https://stackoverflow.com/a/18568726
|
<p>Just like any other simple command, <code>[ ... ]</code> or <code>test</code> requires spaces between its arguments.</p>
<pre class="lang-bash prettyprint-override"><code>if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
</code></pre>
<p>Or</p>
<pre class="lang-bash prettyprint-override"><code>if test "$#" -ne 1; then
echo "Illegal number of parameters"
fi
</code></pre>
<h3>Suggestions</h3>
<p>When in Bash, prefer using <code>[[ ]]</code> instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.</p>
<pre class="lang-none prettyprint-override"><code>[[ $# -ne 1 ]]
</code></pre>
<p>It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with <code>extglob</code>) and regex matching.</p>
<p>The following example checks if arguments are valid. It allows a single argument or two.</p>
<pre class="lang-none prettyprint-override"><code>[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]
</code></pre>
<p>For pure arithmetic expressions, using <code>(( ))</code> to some may still be better, but they are still possible in <code>[[ ]]</code> with its arithmetic operators like <code>-eq</code>, <code>-ne</code>, <code>-lt</code>, <code>-le</code>, <code>-gt</code>, or <code>-ge</code> by placing the expression as a single string argument:</p>
<pre class="lang-none prettyprint-override"><code>A=1
[[ 'A + 1' -eq 2 ]] && echo true ## Prints true.
</code></pre>
<p>That should be helpful if you would need to combine it with other features of <code>[[ ]]</code> as well.</p>
<p>Take note that <code>[[ ]]</code> and <code>(( ))</code> are keywords which have same level of parsing as <code>if</code>, <code>case</code>, <code>while</code>, and <code>for</code>.</p>
<p>Also as <a href="https://stackoverflow.com/users/4412820/dave">Dave</a> suggested, error messages are better sent to stderr so they don't get included when stdout is redirected:</p>
<pre><code>echo "Illegal number of parameters" >&2
</code></pre>
<h3>Exiting the script</h3>
<p>It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the <a href="https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script#comment50847987_18568706">comments</a> by <a href="https://stackoverflow.com/users/1102730/ekangas">ekangas</a> but someone edited this answer to have it with <code>-1</code> as the returned value, so I might as well do it right.</p>
<p><code>-1</code> though accepted by Bash as an argument to <code>exit</code> is not explicitly documented and is not right to be used as a common suggestion. <code>64</code> is also the most formal value since it's defined in <code>sysexits.h</code> with <code>#define EX_USAGE 64 /* command line usage error */</code>. Most tools like <code>ls</code> also return <code>2</code> on invalid arguments. I also used to return <code>2</code> in my scripts but lately I no longer really cared, and simply used <code>1</code> in all errors. But let's just place <code>2</code> here since it's most common and probably not OS-specific.</p>
<pre><code>if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters" >&2
exit 2
fi
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions" rel="noreferrer">Bash Conditional Expressions</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs" rel="noreferrer">Conditional Constructs</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching" rel="noreferrer">Pattern Matching</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting" rel="noreferrer">Word Splitting</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Filename-Expansion" rel="noreferrer">Filename Expansion (prev. Pathname Expansion)</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/html_node/Simple-Commands.html" rel="noreferrer">Simple Commands</a></li>
</ul>
|
<p>Just like any other simple command, <code>[ ... ]</code> or <code>test</code> requires spaces between its arguments.</p> <pre class="lang-bash prettyprint-override"><code>if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" fi </code></pre> <p>Or</p> <pre class="lang-bash prettyprint-override"><code>if test "$#" -ne 1; then echo "Illegal number
|
387, 10355, 31134
|
bash, command-line-arguments, parameter-passing
|
<h1>Check number of arguments passed to a Bash script</h1>
<p>I would like my Bash script to print an error message if the required argument count is not met.</p>
<p>I tried the following code:</p>
<pre><code>#!/bin/bash
echo Script name: $0
echo $# arguments
if [$# -ne 1];
then echo "illegal number of parameters"
fi
</code></pre>
<p>For some unknown reason I've got the following error:</p>
<pre><code>test: line 4: [2: command not found
</code></pre>
<p>What am I doing wrong?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 84
|
bash
|
# Check number of arguments passed to a Bash script
I would like my Bash script to print an error message if the required argument count is not met.
I tried the following code:
```
#!/bin/bash
echo Script name: $0
echo $# arguments
if [$# -ne 1];
then echo "illegal number of parameters"
fi
```
For some unknown reason I've got the following error:
```
test: line 4: [2: command not found
```
What am I doing wrong?
|
Just like any other simple command, `[ ... ]` or `test` requires spaces between its arguments.
```
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
```
Or
```
if test "$#" -ne 1; then
echo "Illegal number of parameters"
fi
```
### Suggestions
When in Bash, prefer using `[[ ]]` instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.
```
[[ $# -ne 1 ]]
```
It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with `extglob`) and regex matching.
The following example checks if arguments are valid. It allows a single argument or two.
```
[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]
```
For pure arithmetic expressions, using `(( ))` to some may still be better, but they are still possible in `[[ ]]` with its arithmetic operators like `-eq`, `-ne`, `-lt`, `-le`, `-gt`, or `-ge` by placing the expression as a single string argument:
```
A=1
[[ 'A + 1' -eq 2 ]] && echo true ## Prints true.
```
That should be helpful if you would need to combine it with other features of `[[ ]]` as well.
Take note that `[[ ]]` and `(( ))` are keywords which have same level of parsing as `if`, `case`, `while`, and `for`.
Also as [Dave](https://stackoverflow.com/users/4412820/dave) suggested, error messages are better sent to stderr so they don't get included when stdout is redirected:
```
echo "Illegal number of parameters" >&2
```
### Exiting the script
It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the [comments](https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script#comment50847987_18568706) by [ekangas](https://stackoverflow.com/users/1102730/ekangas) but someone edited this answer to have it with `-1` as the returned value, so I might as well do it right.
`-1` though accepted by Bash as an argument to `exit` is not explicitly documented and is not right to be used as a common suggestion. `64` is also the most formal value since it's defined in `sysexits.h` with `#define EX_USAGE 64 /* command line usage error */`. Most tools like `ls` also return `2` on invalid arguments. I also used to return `2` in my scripts but lately I no longer really cared, and simply used `1` in all errors. But let's just place `2` here since it's most common and probably not OS-specific.
```
if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters" >&2
exit 2
fi
```
### References
- [Bash Conditional Expressions](https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions)
- [Conditional Constructs](https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs)
- [Pattern Matching](https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching)
- [Word Splitting](https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting)
- [Filename Expansion (prev. Pathname Expansion)](https://www.gnu.org/software/bash/manual/bash.html#Filename-Expansion)
- [Simple Commands](https://www.gnu.org/software/bash/manual/html_node/Simple-Commands.html)
|
10586153
|
How to split a string into an array in Bash?
| 976
|
2012-05-14 15:15:58
|
<p>In a Bash script, I would like to split a line into pieces and store them in an array.</p>
<p>For example, given the line:</p>
<pre><code>Paris, France, Europe
</code></pre>
<p>I would like to have the resulting array to look like so:</p>
<pre><code>array[0] = Paris
array[1] = France
array[2] = Europe
</code></pre>
<p>A simple implementation is preferable; speed does not matter. How can I do it?</p>
| 1,536,472
| 1,291,943
|
2025-09-12 01:53:02
| 10,586,169
| 1,557
|
2012-05-14 15:16:48
| 26,428
|
2018-12-19 14:55:14
|
https://stackoverflow.com/q/10586153
|
https://stackoverflow.com/a/10586169
|
<pre><code>IFS=', ' read -r -a array <<< "$string"
</code></pre>
<p>Note that the characters in <code>$IFS</code> are treated individually as separators so that in this case fields may be separated by <em>either</em> a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially.</p>
<p>To access an individual element:</p>
<pre><code>echo "${array[0]}"
</code></pre>
<p>To iterate over the elements:</p>
<pre><code>for element in "${array[@]}"
do
echo "$element"
done
</code></pre>
<p>To get both the index and the value:</p>
<pre><code>for index in "${!array[@]}"
do
echo "$index ${array[index]}"
done
</code></pre>
<p>The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.</p>
<pre><code>unset "array[1]"
array[42]=Earth
</code></pre>
<p>To get the number of elements in an array:</p>
<pre><code>echo "${#array[@]}"
</code></pre>
<p>As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:</p>
<pre><code>echo "${array[-1]}"
</code></pre>
<p>in any version of Bash (from somewhere after 2.05b):</p>
<pre><code>echo "${array[@]: -1:1}"
</code></pre>
<p>Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.</p>
|
<pre><code>IFS=', ' read -r -a array <<< "$string" </code></pre> <p>Note that the characters in <code>$IFS</code> are treated individually as separators so that in this case fields may be separated by <em>either</em> a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space
|
114, 387, 2193
|
arrays, bash, split
|
<h1>How to split a string into an array in Bash?</h1>
<p>In a Bash script, I would like to split a line into pieces and store them in an array.</p>
<p>For example, given the line:</p>
<pre><code>Paris, France, Europe
</code></pre>
<p>I would like to have the resulting array to look like so:</p>
<pre><code>array[0] = Paris
array[1] = France
array[2] = Europe
</code></pre>
<p>A simple implementation is preferable; speed does not matter. How can I do it?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 85
|
bash
|
# How to split a string into an array in Bash?
In a Bash script, I would like to split a line into pieces and store them in an array.
For example, given the line:
```
Paris, France, Europe
```
I would like to have the resulting array to look like so:
```
array[0] = Paris
array[1] = France
array[2] = Europe
```
A simple implementation is preferable; speed does not matter. How can I do it?
|
```
IFS=', ' read -r -a array <<< "$string"
```
Note that the characters in `$IFS` are treated individually as separators so that in this case fields may be separated by *either* a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially.
To access an individual element:
```
echo "${array[0]}"
```
To iterate over the elements:
```
for element in "${array[@]}"
do
echo "$element"
done
```
To get both the index and the value:
```
for index in "${!array[@]}"
do
echo "$index ${array[index]}"
done
```
The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.
```
unset "array[1]"
array[42]=Earth
```
To get the number of elements in an array:
```
echo "${#array[@]}"
```
As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:
```
echo "${array[-1]}"
```
in any version of Bash (from somewhere after 2.05b):
```
echo "${array[@]: -1:1}"
```
Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.
|
2853803
|
How to echo shell commands as they are executed
| 1,344
|
2010-05-18 00:03:09
|
<p>In a shell script, how do I echo all shell commands called and expand any variable names?</p>
<p>For example, given the following line:</p>
<pre><code>ls $DIRNAME
</code></pre>
<p>I would like the script to run the command and display the following</p>
<pre><code>ls /full/path/to/some/dir
</code></pre>
<p>The purpose is to save a log of all shell commands called and their arguments. Is there perhaps a better way of generating such a log?</p>
| 1,235,008
| 343,547
|
2025-07-15 06:50:06
| 2,853,811
| 1,542
|
2010-05-18 00:06:07
| 63,309
|
2025-01-18 14:26:14
|
https://stackoverflow.com/q/2853803
|
https://stackoverflow.com/a/2853811
|
<p><code>set -x</code> or <code>set -o xtrace</code> expands variables and prints a little + sign before the line.</p>
<p><code>set -v</code> or <code>set -o verbose</code> does not expand the variables before printing.</p>
<p>Use <code>set +x</code> and <code>set +v</code> to turn off the above settings.</p>
<p>On the first line of the script, one can put <code>#!/bin/sh -x</code> (or <code>-v</code>) to have the same effect as <code>set -x</code> (or <code>-v</code>) later in the script.</p>
<p>The above also works with <code>/bin/sh</code>.</p>
<p>See the bash-hackers' wiki on <a href="https://flokoe.github.io/bash-hackers-wiki/commands/builtin/set/#attributes" rel="noreferrer"><code>set</code> attributes</a>, and on <a href="https://flokoe.github.io/bash-hackers-wiki/scripting/debuggingtips/" rel="noreferrer">debugging</a>.</p>
<pre><code>$ cat shl
#!/bin/bash
DIR=/tmp/so
ls $DIR
$ bash -x shl
+ DIR=/tmp/so
+ ls /tmp/so
$
</code></pre>
|
<p><code>set -x</code> or <code>set -o xtrace</code> expands variables and prints a little + sign before the line.</p> <p><code>set -v</code> or <code>set -o verbose</code> does not expand the variables before printing.</p> <p>Use <code>set +x</code> and <code>set +v</code> to turn off the above settings.</p> <p>On the first line of the script, one can put <code>#!/bin/sh -x</code> (or <code>-v</c
|
387, 390, 1441, 1993, 10327
|
bash, posix, sh, shell, trace
|
<h1>How to echo shell commands as they are executed</h1>
<p>In a shell script, how do I echo all shell commands called and expand any variable names?</p>
<p>For example, given the following line:</p>
<pre><code>ls $DIRNAME
</code></pre>
<p>I would like the script to run the command and display the following</p>
<pre><code>ls /full/path/to/some/dir
</code></pre>
<p>The purpose is to save a log of all shell commands called and their arguments. Is there perhaps a better way of generating such a log?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 86
|
bash
|
# How to echo shell commands as they are executed
In a shell script, how do I echo all shell commands called and expand any variable names?
For example, given the following line:
```
ls $DIRNAME
```
I would like the script to run the command and display the following
```
ls /full/path/to/some/dir
```
The purpose is to save a log of all shell commands called and their arguments. Is there perhaps a better way of generating such a log?
|
`set -x` or `set -o xtrace` expands variables and prints a little + sign before the line.
`set -v` or `set -o verbose` does not expand the variables before printing.
Use `set +x` and `set +v` to turn off the above settings.
On the first line of the script, one can put `#!/bin/sh -x` (or `-v`) to have the same effect as `set -x` (or `-v`) later in the script.
The above also works with `/bin/sh`.
See the bash-hackers' wiki on [`set` attributes](https://flokoe.github.io/bash-hackers-wiki/commands/builtin/set/#attributes), and on [debugging](https://flokoe.github.io/bash-hackers-wiki/scripting/debuggingtips/).
```
$ cat shl
#!/bin/bash
DIR=/tmp/so
ls $DIR
$ bash -x shl
+ DIR=/tmp/so
+ ls /tmp/so
$
```
|
1371261
|
Get current directory or folder name (without the full path)
| 1,192
|
2009-09-03 03:11:53
|
<p>How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.</p>
<p><code>pwd</code> gives the full path of the current working directory, e.g. <code>/opt/local/bin</code> but I only want <code>bin</code>.</p>
| 1,035,140
| 86,024
|
2025-01-15 06:09:18
| 1,371,283
| 1,538
|
2009-09-03 03:21:39
| 14,122
|
2024-10-12 01:22:22
|
https://stackoverflow.com/q/1371261
|
https://stackoverflow.com/a/1371283
|
<p>No need for basename, and especially no need for a subshell running pwd (which <A HREF="http://mywiki.wooledge.org/SubShell" rel="noreferrer">adds an extra, and expensive, fork operation</A>); the shell can do this internally using <A HREF="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">parameter expansion</A>:</p>
<pre class="lang-bash prettyprint-override"><code>result=${PWD##*/} # to assign to a variable
result=${result:-/} # to correct for the case where PWD is / (root)
printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
</code></pre>
<hr />
<p>Note that if you're applying this technique in other circumstances (not <code>PWD</code>, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's <a href="http://wiki.bash-hackers.org/syntax/pattern#extended_pattern_language" rel="noreferrer">extglob support</a> to work even with multiple trailing slashes:</p>
<pre class="lang-bash prettyprint-override"><code>dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"
</code></pre>
<p>Alternatively, without <code>extglob</code>:</p>
<pre class="lang-bash prettyprint-override"><code>dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
result=${result:-/} # correct for dirname=/ case
</code></pre>
|
<p>No need for basename, and especially no need for a subshell running pwd (which <A HREF="http://mywiki.wooledge.org/SubShell" rel="noreferrer">adds an extra, and expensive, fork operation</A>); the shell can do this internally using <A HREF="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">parameter expansion</A>:</p> <pre class="lang-bash pretty
|
387, 390
|
bash, shell
|
<h1>Get current directory or folder name (without the full path)</h1>
<p>How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.</p>
<p><code>pwd</code> gives the full path of the current working directory, e.g. <code>/opt/local/bin</code> but I only want <code>bin</code>.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 87
|
bash
|
# Get current directory or folder name (without the full path)
How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.
`pwd` gives the full path of the current working directory, e.g. `/opt/local/bin` but I only want `bin`.
|
No need for basename, and especially no need for a subshell running pwd (which [adds an extra, and expensive, fork operation](http://mywiki.wooledge.org/SubShell)); the shell can do this internally using [parameter expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html):
```
result=${PWD##*/} # to assign to a variable
result=${result:-/} # to correct for the case where PWD is / (root)
printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
```
---
Note that if you're applying this technique in other circumstances (not `PWD`, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's [extglob support](http://wiki.bash-hackers.org/syntax/pattern#extended_pattern_language) to work even with multiple trailing slashes:
```
dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"
```
Alternatively, without `extglob`:
```
dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
result=${result:-/} # correct for dirname=/ case
```
|
2953081
|
How can I write a heredoc to a file in Bash script?
| 1,021
|
2010-06-01 20:28:10
|
<p>How can I write a here document to a file in Bash script?</p>
| 641,780
| 299,408
|
2024-06-07 12:59:49
| 2,954,835
| 1,535
|
2010-06-02 03:40:50
| 110,223
|
2024-06-07 12:59:49
|
https://stackoverflow.com/q/2953081
|
https://stackoverflow.com/a/2954835
|
<p>Read the <a href="https://tldp.org/LDP/abs/html/here-docs.html" rel="noreferrer"><em>Advanced Bash-Scripting Guide — Chapter 19. Here Documents</em></a> and <a href="https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Documents" rel="noreferrer"><em>Bash Reference Manual — Redirections: Here Documents</em></a>.</p>
<p>Here's an example which will write the contents to a file at <code>/tmp/yourfilehere</code></p>
<pre><code>cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
</code></pre>
<p>Note that the final 'EOF' (The <code>LimitString</code>) should not have any whitespace in front of the word, because it means that the <code>LimitString</code> will not be recognized.</p>
<p>In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <code><<-</code> (followed by a dash) to disable leading tabs (<strong>Note</strong> that to test this you will need to <strong>replace the leading whitespace with a tab character</strong>, since I cannot print actual tab characters here.)</p>
<pre><code>#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
</code></pre>
<p>If you don't want to interpret variables in the text, then use single quotes:</p>
<pre><code>cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
</code></pre>
<p>To pipe the heredoc through a command pipeline:</p>
<pre><code>cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
</code></pre>
<p>Output:</p>
<pre><code>foo
bbr
bbz
</code></pre>
<p>... or to write the the heredoc to a file using <code>sudo</code>:</p>
<pre><code>cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
</code></pre>
|
<p>Read the <a href="https://tldp.org/LDP/abs/html/here-docs.html" rel="noreferrer"><em>Advanced Bash-Scripting Guide — Chapter 19. Here Documents</em></a> and <a href="https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Documents" rel="noreferrer"><em>Bash Reference Manual — Redirections: Here Documents</em></a>.</p> <p>Here's an example which will write the contents to a fi
|
387, 7449
|
bash, heredoc
|
<h1>How can I write a heredoc to a file in Bash script?</h1>
<p>How can I write a here document to a file in Bash script?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 88
|
bash
|
# How can I write a heredoc to a file in Bash script?
How can I write a here document to a file in Bash script?
|
Read the [*Advanced Bash-Scripting Guide — Chapter 19. Here Documents*](https://tldp.org/LDP/abs/html/here-docs.html) and [*Bash Reference Manual — Redirections: Here Documents*](https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Documents).
Here's an example which will write the contents to a file at `/tmp/yourfilehere`
```
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
```
Note that the final 'EOF' (The `LimitString`) should not have any whitespace in front of the word, because it means that the `LimitString` will not be recognized.
In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use `<<-` (followed by a dash) to disable leading tabs (**Note** that to test this you will need to **replace the leading whitespace with a tab character**, since I cannot print actual tab characters here.)
```
#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
```
If you don't want to interpret variables in the text, then use single quotes:
```
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
```
To pipe the heredoc through a command pipeline:
```
cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
```
Output:
```
foo
bbr
bbz
```
... or to write the the heredoc to a file using `sudo`:
```
cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
```
|
4997693
|
Given two directory trees, how can I find out which files differ by content?
| 1,060
|
2011-02-14 21:52:07
|
<p>If I want find the differences between two directory trees, I usually just execute:</p>
<pre><code>diff -r dir1/ dir2/
</code></pre>
<p>This outputs exactly what the differences are between corresponding files. I'm interested in just getting a list of corresponding files whose content differs. I assumed that this would simply be a matter of passing a command line option to <code>diff</code>, but I couldn't find anything on the man page.</p>
<p>Any suggestions?</p>
| 789,346
| 477,451
|
2023-04-24 15:26:22
| 4,997,724
| 1,531
|
2011-02-14 21:55:39
| 167,985
|
2021-05-01 03:29:48
|
https://stackoverflow.com/q/4997693
|
https://stackoverflow.com/a/4997724
|
<p>Try:</p>
<pre class="lang-sh prettyprint-override"><code>diff --brief --recursive dir1/ dir2/
</code></pre>
<p>Or alternatively, with the short flags <code>-qr</code>:</p>
<pre class="lang-sh prettyprint-override"><code>diff -qr dir1/ dir2/
</code></pre>
<p>If you also want to see differences for files that may not exist in either directory:</p>
<pre class="lang-sh prettyprint-override"><code>diff --brief --recursive --new-file dir1/ dir2/ # with long options
diff -qrN dir1/ dir2/ # with short flag aliases
</code></pre>
|
<p>Try:</p> <pre class="lang-sh prettyprint-override"><code>diff --brief --recursive dir1/ dir2/ </code></pre> <p>Or alternatively, with the short flags <code>-qr</code>:</p> <pre class="lang-sh prettyprint-override"><code>diff -qr dir1/ dir2/ </code></pre> <p>If you also want to see differences for files that may not exist in either directory:</p> <pre class="lang-sh prettyprint-override"><code>d
|
34, 58, 387, 390, 606
|
bash, diff, linux, shell, unix
|
<h1>Given two directory trees, how can I find out which files differ by content?</h1>
<p>If I want find the differences between two directory trees, I usually just execute:</p>
<pre><code>diff -r dir1/ dir2/
</code></pre>
<p>This outputs exactly what the differences are between corresponding files. I'm interested in just getting a list of corresponding files whose content differs. I assumed that this would simply be a matter of passing a command line option to <code>diff</code>, but I couldn't find anything on the man page.</p>
<p>Any suggestions?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 89
|
bash
|
# Given two directory trees, how can I find out which files differ by content?
If I want find the differences between two directory trees, I usually just execute:
```
diff -r dir1/ dir2/
```
This outputs exactly what the differences are between corresponding files. I'm interested in just getting a list of corresponding files whose content differs. I assumed that this would simply be a matter of passing a command line option to `diff`, but I couldn't find anything on the man page.
Any suggestions?
|
Try:
```
diff --brief --recursive dir1/ dir2/
```
Or alternatively, with the short flags `-qr`:
```
diff -qr dir1/ dir2/
```
If you also want to see differences for files that may not exist in either directory:
```
diff --brief --recursive --new-file dir1/ dir2/ # with long options
diff -qrN dir1/ dir2/ # with short flag aliases
```
|
6674327
|
Redirect all output to file in Bash
| 958
|
2011-07-13 05:06:49
|
<p>I know that in Linux, to redirect output from the screen to a file, I can either use the <code>></code> or <code>tee</code>. However, I'm not sure why part of the output is still output to the screen and not written to the file. </p>
<p>Is there a way to redirect all output to file?</p>
| 1,458,145
| 270,043
|
2021-05-14 21:17:34
| 6,674,348
| 1,514
|
2011-07-13 05:10:01
| 742,469
|
2011-07-13 05:10:01
|
https://stackoverflow.com/q/6674327
|
https://stackoverflow.com/a/6674348
|
<p>That part is written to stderr, use <code>2></code> to redirect it. For example:</p>
<pre><code>foo > stdout.txt 2> stderr.txt
</code></pre>
<p>or if you want in same file:</p>
<pre><code>foo > allout.txt 2>&1
</code></pre>
<p>Note: this works in (ba)sh, check your shell for proper syntax</p>
|
<p>That part is written to stderr, use <code>2></code> to redirect it. For example:</p> <pre><code>foo > stdout.txt 2> stderr.txt </code></pre> <p>or if you want in same file:</p> <pre><code>foo > allout.txt 2>&1 </code></pre> <p>Note: this works in (ba)sh, check your shell for proper syntax</p>
|
58, 387, 26698
|
bash, io-redirection, linux
|
<h1>Redirect all output to file in Bash</h1>
<p>I know that in Linux, to redirect output from the screen to a file, I can either use the <code>></code> or <code>tee</code>. However, I'm not sure why part of the output is still output to the screen and not written to the file. </p>
<p>Is there a way to redirect all output to file?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 90
|
bash
|
# Redirect all output to file in Bash
I know that in Linux, to redirect output from the screen to a file, I can either use the `>` or `tee`. However, I'm not sure why part of the output is still output to the screen and not written to the file.
Is there a way to redirect all output to file?
|
That part is written to stderr, use `2>` to redirect it. For example:
```
foo > stdout.txt 2> stderr.txt
```
or if you want in same file:
```
foo > allout.txt 2>&1
```
Note: this works in (ba)sh, check your shell for proper syntax
|
18668556
|
How can I compare numbers in Bash?
| 983
|
2013-09-07 00:44:38
|
<p>I'm unable to get numeric comparisons working:</p>
<pre class="lang-sh prettyprint-override"><code>echo "enter two numbers";
read a b;
echo "a=$a";
echo "b=$b";
if [ $a \> $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
</code></pre>
<p>The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.</p>
<p>How can I convert the numbers into a type to do a true comparison?</p>
| 1,752,250
| 2,658,664
|
2022-12-06 14:14:02
| 18,668,580
| 1,494
|
2013-09-07 00:48:12
| 1,032,785
|
2021-04-25 16:24:28
|
https://stackoverflow.com/q/18668556
|
https://stackoverflow.com/a/18668580
|
<p>In Bash, you should do your check in an <a href="http://mywiki.wooledge.org/ArithmeticExpression" rel="noreferrer">arithmetic context</a>:</p>
<pre><code>if (( a > b )); then
...
fi
</code></pre>
<p>For POSIX shells that don't support <code>(())</code>, you can use <code>-lt</code> and <code>-gt</code>.</p>
<pre><code>if [ "$a" -gt "$b" ]; then
...
fi
</code></pre>
<p>You can get a full list of comparison operators with <code>help test</code> or <code>man test</code>.</p>
|
<p>In Bash, you should do your check in an <a href="http://mywiki.wooledge.org/ArithmeticExpression" rel="noreferrer">arithmetic context</a>:</p> <pre><code>if (( a > b )); then ... fi </code></pre> <p>For POSIX shells that don't support <code>(())</code>, you can use <code>-lt</code> and <code>-gt</code>.</p> <pre><code>if [ "$a" -gt "$b" ]; then ... fi </code></pre
|
387, 390, 5827
|
bash, numeric, shell
|
<h1>How can I compare numbers in Bash?</h1>
<p>I'm unable to get numeric comparisons working:</p>
<pre class="lang-sh prettyprint-override"><code>echo "enter two numbers";
read a b;
echo "a=$a";
echo "b=$b";
if [ $a \> $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
</code></pre>
<p>The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.</p>
<p>How can I convert the numbers into a type to do a true comparison?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 91
|
bash
|
# How can I compare numbers in Bash?
I'm unable to get numeric comparisons working:
```
echo "enter two numbers";
read a b;
echo "a=$a";
echo "b=$b";
if [ $a \> $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
```
The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.
How can I convert the numbers into a type to do a true comparison?
|
In Bash, you should do your check in an [arithmetic context](http://mywiki.wooledge.org/ArithmeticExpression):
```
if (( a > b )); then
...
fi
```
For POSIX shells that don't support `(())`, you can use `-lt` and `-gt`.
```
if [ "$a" -gt "$b" ]; then
...
fi
```
You can get a full list of comparison operators with `help test` or `man test`.
|
984204
|
Shell command to tar directory excluding certain files/folders
| 1,148
|
2009-06-11 22:57:31
|
<p>Is there a simple shell command/script that supports excluding certain files/folders from being archived?</p>
<p>I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.</p>
<p><strong>Not quite solutions:</strong></p>
<p>The <code>tar --exclude=PATTERN</code> command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.</p>
<p>I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.</p>
<p>I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with <code>--exclude-from=file</code> to copy all the files to a tmp directory, and then use tar to archive that directory.</p>
<p>Can anybody think of a better/more efficient solution?</p>
<p>EDIT: <strong>Charles Ma</strong>'s solution works well. The big gotcha is that the <code>--exclude='./folder'</code> <strong>MUST</strong> be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):</p>
<pre><code>cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
</code></pre>
| 1,403,997
| 21,473
|
2023-11-21 06:38:56
| 984,259
| 1,484
|
2009-06-11 23:11:19
| 11,708
|
2017-05-16 08:15:55
|
https://stackoverflow.com/q/984204
|
https://stackoverflow.com/a/984259
|
<p>You can have multiple exclude options for tar so</p>
<pre><code>$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
</code></pre>
<p>etc will work. Make <strong>sure</strong> to put <code>--exclude</code> <strong>before</strong> the source and destination items. </p>
|
<p>You can have multiple exclude options for tar so</p> <pre><code>$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz . </code></pre> <p>etc will work. Make <strong>sure</strong> to put <code>--exclude</code> <strong>before</strong> the source and destination items. </p>
|
58, 390, 8773, 9655
|
archive, linux, shell, tar
|
<h1>Shell command to tar directory excluding certain files/folders</h1>
<p>Is there a simple shell command/script that supports excluding certain files/folders from being archived?</p>
<p>I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.</p>
<p><strong>Not quite solutions:</strong></p>
<p>The <code>tar --exclude=PATTERN</code> command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.</p>
<p>I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.</p>
<p>I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with <code>--exclude-from=file</code> to copy all the files to a tmp directory, and then use tar to archive that directory.</p>
<p>Can anybody think of a better/more efficient solution?</p>
<p>EDIT: <strong>Charles Ma</strong>'s solution works well. The big gotcha is that the <code>--exclude='./folder'</code> <strong>MUST</strong> be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):</p>
<pre><code>cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 92
|
bash
|
# Shell command to tar directory excluding certain files/folders
Is there a simple shell command/script that supports excluding certain files/folders from being archived?
I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.
**Not quite solutions:**
The `tar --exclude=PATTERN` command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.
I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.
I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with `--exclude-from=file` to copy all the files to a tmp directory, and then use tar to archive that directory.
Can anybody think of a better/more efficient solution?
EDIT: **Charles Ma**'s solution works well. The big gotcha is that the `--exclude='./folder'` **MUST** be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):
```
cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
```
|
You can have multiple exclude options for tar so
```
$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
```
etc will work. Make **sure** to put `--exclude` **before** the source and destination items.
|
2232
|
How to call shell commands from Ruby
| 1,270
|
2008-08-05 12:56:52
|
<p>How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>
| 661,010
| 25
|
2024-09-23 07:21:56
| 2,400
| 1,478
|
2008-08-05 14:42:45
| 402
|
2020-05-07 13:11:15
|
https://stackoverflow.com/q/2232
|
https://stackoverflow.com/a/2400
|
<p>This explanation is based on a commented <a href="http://gist.github.com/4069" rel="noreferrer">Ruby script</a> from a friend of mine. If you want to improve the script, feel free to update it at the link.</p>
<p>First, note that when Ruby calls out to a shell, it typically calls <code>/bin/sh</code>, <em>not</em> Bash. Some Bash syntax is not supported by <code>/bin/sh</code> on all systems.</p>
<p>Here are ways to execute a shell script:</p>
<pre><code>cmd = "echo 'hi'" # Sample string that can be used
</code></pre>
<ol>
<li><p><code>Kernel#`</code> , commonly called backticks – <code>`cmd`</code></p>
<p>This is like many other languages, including Bash, PHP, and Perl.</p>
<p>Returns the result (i.e. standard output) of the shell command.</p>
<p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-60" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-60</a></p>
<pre><code>value = `echo 'hi'`
value = `#{cmd}`
</code></pre></li>
<li><p>Built-in syntax, <code>%x( cmd )</code></p>
<p>Following the <code>x</code> character is a delimiter, which can be any character.
If the delimiter is one of the characters <code>(</code>, <code>[</code>, <code>{</code>, or <code><</code>,
the literal consists of the characters up to the matching closing delimiter,
taking account of nested delimiter pairs. For all other delimiters, the
literal comprises the characters up to the next occurrence of the
delimiter character. String interpolation <code>#{ ... }</code> is allowed.</p>
<p>Returns the result (i.e. standard output) of the shell command, just like the backticks.</p>
<p>Docs: <a href="https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings" rel="noreferrer">https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings</a></p>
<pre><code>value = %x( echo 'hi' )
value = %x[ #{cmd} ]
</code></pre></li>
<li><p><code>Kernel#system</code></p>
<p>Executes the given command in a subshell. </p>
<p>Returns <code>true</code> if the command was found and run successfully, <code>false</code> otherwise.</p>
<p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-system" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-system</a></p>
<pre><code>wasGood = system( "echo 'hi'" )
wasGood = system( cmd )
</code></pre></li>
<li><p><code>Kernel#exec</code></p>
<p>Replaces the current process by running the given external command.</p>
<p>Returns none, the current process is replaced and never continues.</p>
<p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-exec" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-exec</a></p>
<pre><code>exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached because of the line above
</code></pre></li>
</ol>
<p>Here's some extra advice:
<code>$?</code>, which is the same as <code>$CHILD_STATUS</code>, accesses the status of the last system executed command if you use the backticks, <code>system()</code> or <code>%x{}</code>.
You can then access the <code>exitstatus</code> and <code>pid</code> properties:</p>
<pre><code>$?.exitstatus
</code></pre>
<p>For more reading see:</p>
<ul>
<li><a href="http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands" rel="noreferrer">http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands</a></li>
<li><a href="http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html" rel="noreferrer">http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html</a></li>
<li><a href="http://tech.natemurray.com/2007/03/ruby-shell-commands.html" rel="noreferrer">http://tech.natemurray.com/2007/03/ruby-shell-commands.html</a></li>
</ul>
|
<p>This explanation is based on a commented <a href="http://gist.github.com/4069" rel="noreferrer">Ruby script</a> from a friend of mine. If you want to improve the script, feel free to update it at the link.</p> <p>First, note that when Ruby calls out to a shell, it typically calls <code>/bin/sh</code>, <em>not</em> Bash. Some Bash syntax is not supported by <code>/bin/sh</code> on all systems.<
|
12, 390, 1592
|
interop, ruby, shell
|
<h1>How to call shell commands from Ruby</h1>
<p>How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 93
|
bash
|
# How to call shell commands from Ruby
How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
|
This explanation is based on a commented [Ruby script](http://gist.github.com/4069) from a friend of mine. If you want to improve the script, feel free to update it at the link.
First, note that when Ruby calls out to a shell, it typically calls `/bin/sh`, *not* Bash. Some Bash syntax is not supported by `/bin/sh` on all systems.
Here are ways to execute a shell script:
```
cmd = "echo 'hi'" # Sample string that can be used
```
1. `` Kernel#` `` , commonly called backticks – `` `cmd` ``
This is like many other languages, including Bash, PHP, and Perl.
Returns the result (i.e. standard output) of the shell command.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-60>
```
value = `echo 'hi'`
value = `#{cmd}`
```
2. Built-in syntax, `%x( cmd )`
Following the `x` character is a delimiter, which can be any character.
If the delimiter is one of the characters `(`, `[`, `{`, or `<`,
the literal consists of the characters up to the matching closing delimiter,
taking account of nested delimiter pairs. For all other delimiters, the
literal comprises the characters up to the next occurrence of the
delimiter character. String interpolation `#{ ... }` is allowed.
Returns the result (i.e. standard output) of the shell command, just like the backticks.
Docs: <https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings>
```
value = %x( echo 'hi' )
value = %x[ #{cmd} ]
```
3. `Kernel#system`
Executes the given command in a subshell.
Returns `true` if the command was found and run successfully, `false` otherwise.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-system>
```
wasGood = system( "echo 'hi'" )
wasGood = system( cmd )
```
4. `Kernel#exec`
Replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.
Docs: <http://ruby-doc.org/core/Kernel.html#method-i-exec>
```
exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached because of the line above
```
Here's some extra advice:
`$?`, which is the same as `$CHILD_STATUS`, accesses the status of the last system executed command if you use the backticks, `system()` or `%x{}`.
You can then access the `exitstatus` and `pid` properties:
```
$?.exitstatus
```
For more reading see:
- <http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands>
- <http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html>
- <http://tech.natemurray.com/2007/03/ruby-shell-commands.html>
|
7342597
|
How do you comment out code in PowerShell?
| 1,116
|
2011-09-08 02:43:10
|
<p>How do you comment out code in <strong>PowerShell</strong> (1.0 or 2.0)?</p>
| 1,059,155
| 528,383
|
2025-03-23 21:05:19
| 7,344,038
| 1,471
|
2011-09-08 06:33:59
| 608,772
|
2021-09-07 12:21:07
|
https://stackoverflow.com/q/7342597
|
https://stackoverflow.com/a/7344038
|
<p>In PowerShell V1 there's only <code>#</code> to make the text after it a comment.</p>
<pre class="lang-powershell prettyprint-override"><code># This is a comment in PowerShell
</code></pre>
<p>In PowerShell V2 <code><# #></code> can be used for block comments and more specifically for help comments.</p>
<pre class="lang-none prettyprint-override"><code>#REQUIRES -Version 2.0
<#
.SYNOPSIS
A brief description of the function or script. This keyword can be used
only once in each topic.
.DESCRIPTION
A detailed description of the function or script. This keyword can be
used only once in each topic.
.NOTES
File Name : xxxx.ps1
Author : J.P. Blanc (jean-paul_blanc@silogix-fr.com)
Prerequisite : PowerShell V2 over Vista and upper.
Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
Script posted over:
http://silogix.fr
.EXAMPLE
Example 1
.EXAMPLE
Example 2
#>
Function blabla
{}
</code></pre>
<p>For more explanation about <code>.SYNOPSIS</code> and <code>.*</code> see <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-7.1" rel="noreferrer">about_Comment_Based_Help</a>.</p>
<p>Remark: These function comments are used by the <code>Get-Help</code> CmdLet and can be put before the keyword <code>Function</code>, or inside the <code>{}</code> before or after the code itself.</p>
|
<p>In PowerShell V1 there's only <code>#</code> to make the text after it a comment.</p> <pre class="lang-powershell prettyprint-override"><code># This is a comment in PowerShell </code></pre> <p>In PowerShell V2 <code><# #></code> can be used for block comments and more specifically for help comments.</p> <pre class="lang-none prettyprint-override"><code>#REQUIRES -Version 2.0 <# .SYNOP
|
367, 526, 1966, 24067
|
comments, powershell, powershell-2.0, syntax
|
<h1>How do you comment out code in PowerShell?</h1>
<p>How do you comment out code in <strong>PowerShell</strong> (1.0 or 2.0)?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 94
|
bash
|
# How do you comment out code in PowerShell?
How do you comment out code in **PowerShell** (1.0 or 2.0)?
|
In PowerShell V1 there's only `#` to make the text after it a comment.
```
# This is a comment in PowerShell
```
In PowerShell V2 `<# #>` can be used for block comments and more specifically for help comments.
```
#REQUIRES -Version 2.0
<#
.SYNOPSIS
A brief description of the function or script. This keyword can be used
only once in each topic.
.DESCRIPTION
A detailed description of the function or script. This keyword can be
used only once in each topic.
.NOTES
File Name : xxxx.ps1
Author : J.P. Blanc (jean-paul_blanc@silogix-fr.com)
Prerequisite : PowerShell V2 over Vista and upper.
Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
Script posted over:
http://silogix.fr
.EXAMPLE
Example 1
.EXAMPLE
Example 2
#>
Function blabla
{}
```
For more explanation about `.SYNOPSIS` and `.*` see [about_Comment_Based_Help](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-7.1).
Remark: These function comments are used by the `Get-Help` CmdLet and can be put before the keyword `Function`, or inside the `{}` before or after the code itself.
|
1885525
|
How do I prompt a user for confirmation in bash script?
| 877
|
2009-12-11 02:52:46
|
<p>I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?</p>
| 579,501
| 3,715
|
2023-08-30 19:03:43
| 1,885,534
| 1,458
|
2009-12-11 02:56:30
| 26,428
|
2020-07-27 18:37:28
|
https://stackoverflow.com/q/1885525
|
https://stackoverflow.com/a/1885534
|
<pre class="lang-sh prettyprint-override"><code>read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
</code></pre>
<p>I incorporated <strong>levislevis85</strong>'s suggestion (thanks!) and added the <code>-n</code> option to <code>read</code> to accept one character without the need to press <kbd>Enter</kbd>. You can use one or both of these.</p>
<p>Also, the negated form might look like this:</p>
<pre class="lang-sh prettyprint-override"><code>read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi
</code></pre>
<p>However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated <code>if</code> should be used.</p>
<h2>Explanation:</h2>
<p>The <code>read</code> command outputs the prompt (<code>-p "prompt"</code>) then accepts one character (<code>-n 1</code>) and accepts backslashes literally (<code>-r</code>) (otherwise <code>read</code> would see the backslash as an escape and wait for a second character). The default variable for <code>read</code> to store the result in is <code>$REPLY</code> if you don't supply a name like this: <code>read -p "my prompt" -n 1 -r my_var</code></p>
<p>The <code>if</code> statement uses a regular expression to check if the character in <code>$REPLY</code> matches (<code>=~</code>) an upper or lower case "Y". The regular expression used here says "a string starting (<code>^</code>) and consisting solely of one of a list of characters in a bracket expression (<code>[Yy]</code>) and ending (<code>$</code>)". The anchors (<code>^</code> and <code>$</code>) prevent matching longer strings. In this case they help reinforce the one-character limit set in the <code>read</code> command.</p>
<p>The negated form uses the logical "not" operator (<code>!</code>) to match (<code>=~</code>) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: <code>if [[ $REPLY =~ ^[^Yy]$ ]]</code></p>
|
<pre class="lang-sh prettyprint-override"><code>read -p "Are you sure? " -n 1 -r echo # (optional) move to a new line if [[ $REPLY =~ ^[Yy]$ ]] then # do dangerous stuff fi </code></pre> <p>I incorporated <strong>levislevis85</strong>'s suggestion (thanks!) and added the <code>-n</code> option to <code>read</code> to accept one character without the need to press <kbd>Enter</kbd>.
|
387
|
bash
|
<h1>How do I prompt a user for confirmation in bash script?</h1>
<p>I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 95
|
bash
|
# How do I prompt a user for confirmation in bash script?
I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?
|
```
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
```
I incorporated **levislevis85**'s suggestion (thanks!) and added the `-n` option to `read` to accept one character without the need to press `Enter`. You can use one or both of these.
Also, the negated form might look like this:
```
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi
```
However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated `if` should be used.
## Explanation:
The `read` command outputs the prompt (`-p "prompt"`) then accepts one character (`-n 1`) and accepts backslashes literally (`-r`) (otherwise `read` would see the backslash as an escape and wait for a second character). The default variable for `read` to store the result in is `$REPLY` if you don't supply a name like this: `read -p "my prompt" -n 1 -r my_var`
The `if` statement uses a regular expression to check if the character in `$REPLY` matches (`=~`) an upper or lower case "Y". The regular expression used here says "a string starting (`^`) and consisting solely of one of a list of characters in a bracket expression (`[Yy]`) and ending (`$`)". The anchors (`^` and `$`) prevent matching longer strings. In this case they help reinforce the one-character limit set in the `read` command.
The negated form uses the logical "not" operator (`!`) to match (`=~`) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: `if [[ $REPLY =~ ^[^Yy]$ ]]`
|
1494178
|
How to define hash tables in Bash?
| 875
|
2009-09-29 18:29:38
|
<p>What is the equivalent of <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="noreferrer">Python dictionaries</a> but in Bash (should work across OS X and Linux).</p>
| 797,797
| 55,246
|
2024-04-12 13:13:16
| 3,467,959
| 1,454
|
2010-08-12 13:09:35
| 58,803
|
2021-11-03 21:14:42
|
https://stackoverflow.com/q/1494178
|
https://stackoverflow.com/a/3467959
|
<h1>Bash 4</h1>
<p>Bash 4 natively supports this feature. Make sure your script's hashbang is <code>#!/usr/bin/env bash</code> or <code>#!/bin/bash</code> so you don't end up using <code>sh</code>. Make sure you're either executing your script directly, or execute <code>script</code> with <code>bash script</code>. (Not actually executing a Bash script with Bash <em>does</em> happen, and will be <em>really</em> confusing!)</p>
<p>You declare an associative array by doing:</p>
<pre><code>declare -A animals
</code></pre>
<p>You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of <code>animal[sound(key)] = animal(value)</code>:</p>
<pre><code>animals=( ["moo"]="cow" ["woof"]="dog")
</code></pre>
<p>Or declare and instantiate in one line:</p>
<pre><code>declare -A animals=( ["moo"]="cow" ["woof"]="dog")
</code></pre>
<p>Then use them just like normal arrays. Use</p>
<ul>
<li><p><code>animals['key']='value'</code> to set value</p>
</li>
<li><p><code>"${animals[@]}"</code> to expand the values</p>
</li>
<li><p><code>"${!animals[@]}"</code> (notice the <code>!</code>) to expand the keys</p>
</li>
</ul>
<p>Don't forget to quote them:</p>
<pre><code>echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done
</code></pre>
<h1>Bash 3</h1>
<p>Before bash 4, you don't have associative arrays. <strong>Do not use <code>eval</code> to emulate them</strong>. Avoid <code>eval</code> like the plague, because it <em>is</em> the plague of shell scripting. The most important reason is that <code>eval</code> treats your data as executable code (there are many other reasons too).</p>
<p><em>First and foremost</em>: Consider upgrading to bash 4. This will make the whole process much easier for you.</p>
<p>If there's a reason you can't upgrade, <code>declare</code> is a far safer option. It does not evaluate data as bash code like <code>eval</code> does, and as such does not allow arbitrary code injection quite so easily.</p>
<p>Let's prepare the answer by introducing the concepts:</p>
<p>First, indirection.</p>
<pre><code>$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow
</code></pre>
<p>Secondly, <code>declare</code>:</p>
<pre><code>$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow
</code></pre>
<p>Bring them together:</p>
<pre><code># Set a value:
declare "array_$index=$value"
# Get a value:
arrayGet() {
local array=$1 index=$2
local i="${array}_$index"
printf '%s' "${!i}"
}
</code></pre>
<p>Let's use it:</p>
<pre><code>$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow
</code></pre>
<p>Note: <code>declare</code> cannot be put in a function. Any use of <code>declare</code> inside a bash function turns the variable it creates <em>local</em> to the scope of that function, meaning we can't access or modify global arrays with it. (In bash 4 you can use <code>declare -g</code> to declare global variables - but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)</p>
<p>Summary:</p>
<ul>
<li>Upgrade to bash 4 and use <code>declare -A</code> for associative arrays.</li>
<li>Use the <code>declare</code> option if you can't upgrade.</li>
<li>Consider using <code>awk</code> instead and avoid the issue altogether.</li>
</ul>
|
<h1>Bash 4</h1> <p>Bash 4 natively supports this feature. Make sure your script's hashbang is <code>#!/usr/bin/env bash</code> or <code>#!/bin/bash</code> so you don't end up using <code>sh</code>. Make sure you're either executing your script directly, or execute <code>script</code> with <code>bash script</code>. (Not actually executing a Bash script with Bash <em>does</em> happen, and will be
|
387, 1834, 2575, 5189
|
associative-array, bash, dictionary, hashtable
|
<h1>How to define hash tables in Bash?</h1>
<p>What is the equivalent of <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="noreferrer">Python dictionaries</a> but in Bash (should work across OS X and Linux).</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 96
|
bash
|
# How to define hash tables in Bash?
What is the equivalent of [Python dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) but in Bash (should work across OS X and Linux).
|
# Bash 4
Bash 4 natively supports this feature. Make sure your script's hashbang is `#!/usr/bin/env bash` or `#!/bin/bash` so you don't end up using `sh`. Make sure you're either executing your script directly, or execute `script` with `bash script`. (Not actually executing a Bash script with Bash *does* happen, and will be *really* confusing!)
You declare an associative array by doing:
```
declare -A animals
```
You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of `animal[sound(key)] = animal(value)`:
```
animals=( ["moo"]="cow" ["woof"]="dog")
```
Or declare and instantiate in one line:
```
declare -A animals=( ["moo"]="cow" ["woof"]="dog")
```
Then use them just like normal arrays. Use
- `animals['key']='value'` to set value
- `"${animals[@]}"` to expand the values
- `"${!animals[@]}"` (notice the `!`) to expand the keys
Don't forget to quote them:
```
echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done
```
# Bash 3
Before bash 4, you don't have associative arrays. **Do not use `eval` to emulate them**. Avoid `eval` like the plague, because it *is* the plague of shell scripting. The most important reason is that `eval` treats your data as executable code (there are many other reasons too).
*First and foremost*: Consider upgrading to bash 4. This will make the whole process much easier for you.
If there's a reason you can't upgrade, `declare` is a far safer option. It does not evaluate data as bash code like `eval` does, and as such does not allow arbitrary code injection quite so easily.
Let's prepare the answer by introducing the concepts:
First, indirection.
```
$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow
```
Secondly, `declare`:
```
$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow
```
Bring them together:
```
# Set a value:
declare "array_$index=$value"
# Get a value:
arrayGet() {
local array=$1 index=$2
local i="${array}_$index"
printf '%s' "${!i}"
}
```
Let's use it:
```
$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow
```
Note: `declare` cannot be put in a function. Any use of `declare` inside a bash function turns the variable it creates *local* to the scope of that function, meaning we can't access or modify global arrays with it. (In bash 4 you can use `declare -g` to declare global variables - but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)
Summary:
- Upgrade to bash 4 and use `declare -A` for associative arrays.
- Use the `declare` option if you can't upgrade.
- Consider using `awk` instead and avoid the issue altogether.
|
339483
|
How can I remove the first line of a text file using bash/sed script?
| 816
|
2008-12-04 02:50:16
|
<p>I need to repeatedly remove the first line from a huge text file using a bash script.</p>
<p>Right now I am using <code>sed -i -e "1d" $FILE</code> - but it takes around a minute to do the deletion.</p>
<p>Is there a more efficient way to accomplish this?</p>
| 846,296
| 3,764
|
2025-03-27 07:43:44
| 339,941
| 1,440
|
2008-12-04 08:55:16
| 34,088
|
2019-03-17 12:29:32
|
https://stackoverflow.com/q/339483
|
https://stackoverflow.com/a/339941
|
<p>Try <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer">tail</a>:</p>
<pre><code>tail -n +2 "$FILE"
</code></pre>
<p><code>-n x</code>: Just print the last <code>x</code> lines. <code>tail -n 5</code> would give you the last 5 lines of the input. The <code>+</code> sign kind of inverts the argument and make <code>tail</code> print anything but the first <code>x-1</code> lines. <code>tail -n +1</code> would print the whole file, <code>tail -n +2</code> everything but the first line, etc.</p>
<p>GNU <code>tail</code> is much faster than <code>sed</code>. <code>tail</code> is also available on BSD and the <code>-n +2</code> flag is consistent across both tools. Check the <a href="https://www.freebsd.org/cgi/man.cgi?query=tail" rel="noreferrer">FreeBSD</a> or <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html" rel="noreferrer">OS X</a> man pages for more. </p>
<p>The BSD version can be much slower than <code>sed</code>, though. I wonder how they managed that; <code>tail</code> should just read a file line by line while <code>sed</code> does pretty complex operations involving interpreting a script, applying regular expressions and the like.</p>
<p>Note: You may be tempted to use</p>
<pre><code># THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"
</code></pre>
<p>but this will give you an <strong>empty file</strong>. The reason is that the redirection (<code>></code>) happens before <code>tail</code> is invoked by the shell:</p>
<ol>
<li>Shell truncates file <code>$FILE</code></li>
<li>Shell creates a new process for <code>tail</code></li>
<li>Shell redirects stdout of the <code>tail</code> process to <code>$FILE</code></li>
<li><code>tail</code> reads from the now empty <code>$FILE</code></li>
</ol>
<p>If you want to remove the first line inside the file, you should use:</p>
<pre><code>tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"
</code></pre>
<p>The <code>&&</code> will make sure that the file doesn't get overwritten when there is a problem.</p>
|
<p>Try <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer">tail</a>:</p> <pre><code>tail -n +2 "$FILE" </code></pre> <p><code>-n x</code>: Just print the last <code>x</code> lines. <code>tail -n 5</code> would give you the last 5 lines of the input. The <code>+</code> sign kind of inverts the argument and make <code>tail</code> print anything but the first <code>x-1</code
|
387, 531, 5282
|
bash, scripting, sed
|
<h1>How can I remove the first line of a text file using bash/sed script?</h1>
<p>I need to repeatedly remove the first line from a huge text file using a bash script.</p>
<p>Right now I am using <code>sed -i -e "1d" $FILE</code> - but it takes around a minute to do the deletion.</p>
<p>Is there a more efficient way to accomplish this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 97
|
bash
|
# How can I remove the first line of a text file using bash/sed script?
I need to repeatedly remove the first line from a huge text file using a bash script.
Right now I am using `sed -i -e "1d" $FILE` - but it takes around a minute to do the deletion.
Is there a more efficient way to accomplish this?
|
Try [tail](http://man7.org/linux/man-pages/man1/tail.1.html):
```
tail -n +2 "$FILE"
```
`-n x`: Just print the last `x` lines. `tail -n 5` would give you the last 5 lines of the input. The `+` sign kind of inverts the argument and make `tail` print anything but the first `x-1` lines. `tail -n +1` would print the whole file, `tail -n +2` everything but the first line, etc.
GNU `tail` is much faster than `sed`. `tail` is also available on BSD and the `-n +2` flag is consistent across both tools. Check the [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=tail) or [OS X](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html) man pages for more.
The BSD version can be much slower than `sed`, though. I wonder how they managed that; `tail` should just read a file line by line while `sed` does pretty complex operations involving interpreting a script, applying regular expressions and the like.
Note: You may be tempted to use
```
# THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"
```
but this will give you an **empty file**. The reason is that the redirection (`>`) happens before `tail` is invoked by the shell:
1. Shell truncates file `$FILE`
2. Shell creates a new process for `tail`
3. Shell redirects stdout of the `tail` process to `$FILE`
4. `tail` reads from the now empty `$FILE`
If you want to remove the first line inside the file, you should use:
```
tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"
```
The `&&` will make sure that the file doesn't get overwritten when there is a problem.
|
44656515
|
How to remove double-quotes in jq output for parsing json files in bash?
| 789
|
2017-06-20 14:55:19
|
<p>I'm using jq to parse a JSON file as shown <a href="http://xmodulo.com/how-to-parse-json-string-via-command-line-on-linux.html#comment-13001" rel="nofollow noreferrer">here</a>. However, the results for string values contain the "double-quotes" as expected:</p>
<pre class="lang-none prettyprint-override"><code>$ cat json.txt | jq '.name'
"Google"
</code></pre>
<p>How can I pipe this into another command to remove the ""?</p>
<pre class="lang-none prettyprint-override"><code>$ cat json.txt | jq '.name' | other_command
Google
</code></pre>
| 400,194
| 1,401,560
|
2025-12-03 00:19:08
| 44,656,583
| 1,419
|
2017-06-20 14:58:03
| 14,122
|
2019-10-08 10:59:08
|
https://stackoverflow.com/q/44656515
|
https://stackoverflow.com/a/44656583
|
<p>Use the <code>-r</code> (or <code>--raw-output</code>) option to emit raw strings as output:</p>
<pre><code>jq -r '.name' <json.txt
</code></pre>
|
<p>Use the <code>-r</code> (or <code>--raw-output</code>) option to emit raw strings as output:</p> <pre><code>jq -r '.name' <json.txt </code></pre>
|
387, 990, 5282, 105170
|
awk, bash, jq, sed
|
<h1>How to remove double-quotes in jq output for parsing json files in bash?</h1>
<p>I'm using jq to parse a JSON file as shown <a href="http://xmodulo.com/how-to-parse-json-string-via-command-line-on-linux.html#comment-13001" rel="nofollow noreferrer">here</a>. However, the results for string values contain the "double-quotes" as expected:</p>
<pre class="lang-none prettyprint-override"><code>$ cat json.txt | jq '.name'
"Google"
</code></pre>
<p>How can I pipe this into another command to remove the ""?</p>
<pre class="lang-none prettyprint-override"><code>$ cat json.txt | jq '.name' | other_command
Google
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 98
|
bash
|
# How to remove double-quotes in jq output for parsing json files in bash?
I'm using jq to parse a JSON file as shown [here](http://xmodulo.com/how-to-parse-json-string-via-command-line-on-linux.html#comment-13001). However, the results for string values contain the "double-quotes" as expected:
```
$ cat json.txt | jq '.name'
"Google"
```
How can I pipe this into another command to remove the ""?
```
$ cat json.txt | jq '.name' | other_command
Google
```
|
Use the `-r` (or `--raw-output`) option to emit raw strings as output:
```
jq -r '.name' <json.txt
```
|
1158091
|
Defining a variable with or without export
| 1,274
|
2009-07-21 09:09:57
|
<p>What is <code>export</code> for?</p>
<p>What is the difference between:</p>
<pre><code>export name=value
</code></pre>
<p>and</p>
<pre><code>name=value
</code></pre>
| 550,806
| 63,051
|
2025-01-14 21:38:02
| 1,158,231
| 1,393
|
2009-07-21 09:45:52
| 12,960
|
2025-01-14 21:38:02
|
https://stackoverflow.com/q/1158091
|
https://stackoverflow.com/a/1158231
|
<p><code>export</code> makes the variable available to sub-processes.</p>
<p>That is,</p>
<pre><code>export name=value
</code></pre>
<p>means that the variable name is available to <em>any process</em> you run from that shell process. If you want a process to make use of this variable, use <code>export</code>, and run the process from that shell.</p>
<pre><code>name=value
</code></pre>
<p>means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc. An important exception to this rule is that if you define the variable while running a command, that variable <em>will</em> be available to child processes. For example</p>
<pre><code>MY_VAR=yay node my-script.js
</code></pre>
<p>In this case <code>MY_VAR</code> will be available to the node process running <code>my-script</code>.</p>
<p>It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.</p>
|
<p><code>export</code> makes the variable available to sub-processes.</p> <p>That is,</p> <pre><code>export name=value </code></pre> <p>means that the variable name is available to <em>any process</em> you run from that shell process. If you want a process to make use of this variable, use <code>export</code>, and run the process from that shell.</p> <pre><code>name=value </code></pre> <p>means th
|
58, 387, 390
|
bash, linux, shell
|
<h1>Defining a variable with or without export</h1>
<p>What is <code>export</code> for?</p>
<p>What is the difference between:</p>
<pre><code>export name=value
</code></pre>
<p>and</p>
<pre><code>name=value
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 99
|
bash
|
# Defining a variable with or without export
What is `export` for?
What is the difference between:
```
export name=value
```
and
```
name=value
```
|
`export` makes the variable available to sub-processes.
That is,
```
export name=value
```
means that the variable name is available to *any process* you run from that shell process. If you want a process to make use of this variable, use `export`, and run the process from that shell.
```
name=value
```
means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc. An important exception to this rule is that if you define the variable while running a command, that variable *will* be available to child processes. For example
```
MY_VAR=yay node my-script.js
```
In this case `MY_VAR` will be available to the node process running `my-script`.
It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.
|
8866041
|
How can I list all collections in the MongoDB shell?
| 943
|
2012-01-14 22:52:03
|
<p>In the MongoDB shell, how do I list all collections for the current database that I'm using?</p>
| 1,136,210
| 271,697
|
2026-01-08 13:54:01
| 8,866,075
| 1,389
|
2012-01-14 22:57:47
| 135,531
|
2026-01-08 13:50:29
|
https://stackoverflow.com/q/8866041
|
https://stackoverflow.com/a/8866075
|
<p>You can do...</p>
<p>JavaScript (shell):</p>
<pre class="lang-javascript prettyprint-override"><code>db.getCollectionNames()
</code></pre>
<p>Node.js:</p>
<pre class="lang-javascript prettyprint-override"><code>db.listCollections()
</code></pre>
<p>Non-JavaScript (shell only):</p>
<pre class="lang-none prettyprint-override"><code>show collections
</code></pre>
<p>The reason I call that non-JavaScript is because:</p>
<pre class="lang-none prettyprint-override"><code>$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell eval):1:5
$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
"Profiles",
"Unit_Info"
]
</code></pre>
<p>If you really want that sweet, sweet <code>show collections</code> output, you can:</p>
<pre class="lang-none prettyprint-override"><code>$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
</code></pre>
|
<p>You can do...</p> <p>JavaScript (shell):</p> <pre class="lang-javascript prettyprint-override"><code>db.getCollectionNames() </code></pre> <p>Node.js:</p> <pre class="lang-javascript prettyprint-override"><code>db.listCollections() </code></pre> <p>Non-JavaScript (shell only):</p> <pre class="lang-none prettyprint-override"><code>show collections </code></pre> <p>The reason I call that non-Java
|
30073, 69521
|
mongodb, mongo-shell
|
<h1>How can I list all collections in the MongoDB shell?</h1>
<p>In the MongoDB shell, how do I list all collections for the current database that I'm using?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 100
|
bash
|
# How can I list all collections in the MongoDB shell?
In the MongoDB shell, how do I list all collections for the current database that I'm using?
|
You can do...
JavaScript (shell):
```
db.getCollectionNames()
```
Node.js:
```
db.listCollections()
```
Non-JavaScript (shell only):
```
show collections
```
The reason I call that non-JavaScript is because:
```
$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell eval):1:5
$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
"Profiles",
"Unit_Info"
]
```
If you really want that sweet, sweet `show collections` output, you can:
```
$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
```
|
525592
|
Find and Replace Inside a Text File from a Bash Command
| 858
|
2009-02-08 11:57:39
|
<p>What's the simplest way to do a find and replace for a given input string, say <code>abc</code>, and replace with another string, say <code>XYZ</code> in file <code>/tmp/file.txt</code>?</p>
<p>I am writing an app and using IronPython to execute commands through SSH — but I don't know Unix that well and don't know what to look for.</p>
<p>I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. If this is true, I assume you can perform actions like these.</p>
<p>Can I do it with Bash, and what's the simplest (one line) script to achieve my goal?</p>
| 1,064,283
| 11,194
|
2024-01-03 05:27:36
| 525,612
| 1,386
|
2009-02-08 12:20:29
| 61,097
|
2024-01-03 05:27:36
|
https://stackoverflow.com/q/525592
|
https://stackoverflow.com/a/525612
|
<p>The easiest way is to use <code>sed</code> (or Perl):</p>
<pre class="lang-bash prettyprint-override"><code>sed -i -e 's/abc/XYZ/g' /tmp/file.txt
</code></pre>
<p>which will invoke <code>sed</code> to do an in-place edit due to the <code>-i</code> option. The <code>/g</code> flag for <code>sed</code>'s <code>s</code> command says to replace globally, i.e. do not substitute only the first occurrence on each input line. This can be called from Bash.</p>
<p>(The <code>-i</code> option is not standard. On BSD-based platforms, including MacOS, you need an explicit option argument <code>-i ''</code>.)</p>
<p>If you really really want to use just Bash, then the following can work:</p>
<pre class="lang-bash prettyprint-override"><code>while IFS='' read -r a; do
echo "${a//abc/XYZ}"
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}
</code></pre>
<p>This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The <code>mv</code> at the end just moves the temporary file to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)</p>
<p>This uses a Bash-only <a href="https://www.gnu.org/s/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">parameter expansion</a> to perform a replacement on the variable's value.</p>
|
<p>The easiest way is to use <code>sed</code> (or Perl):</p> <pre class="lang-bash prettyprint-override"><code>sed -i -e 's/abc/XYZ/g' /tmp/file.txt </code></pre> <p>which will invoke <code>sed</code> to do an in-place edit due to the <code>-i</code> option. The <code>/g</code> flag for <code>sed</code>'s <code>s</code> command says to replace globally, i.e. do not substitute only the first occur
|
387, 531, 1589, 2498
|
bash, ironpython, replace, scripting
|
<h1>Find and Replace Inside a Text File from a Bash Command</h1>
<p>What's the simplest way to do a find and replace for a given input string, say <code>abc</code>, and replace with another string, say <code>XYZ</code> in file <code>/tmp/file.txt</code>?</p>
<p>I am writing an app and using IronPython to execute commands through SSH — but I don't know Unix that well and don't know what to look for.</p>
<p>I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. If this is true, I assume you can perform actions like these.</p>
<p>Can I do it with Bash, and what's the simplest (one line) script to achieve my goal?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 101
|
bash
|
# Find and Replace Inside a Text File from a Bash Command
What's the simplest way to do a find and replace for a given input string, say `abc`, and replace with another string, say `XYZ` in file `/tmp/file.txt`?
I am writing an app and using IronPython to execute commands through SSH — but I don't know Unix that well and don't know what to look for.
I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. If this is true, I assume you can perform actions like these.
Can I do it with Bash, and what's the simplest (one line) script to achieve my goal?
|
The easiest way is to use `sed` (or Perl):
```
sed -i -e 's/abc/XYZ/g' /tmp/file.txt
```
which will invoke `sed` to do an in-place edit due to the `-i` option. The `/g` flag for `sed`'s `s` command says to replace globally, i.e. do not substitute only the first occurrence on each input line. This can be called from Bash.
(The `-i` option is not standard. On BSD-based platforms, including MacOS, you need an explicit option argument `-i ''`.)
If you really really want to use just Bash, then the following can work:
```
while IFS='' read -r a; do
echo "${a//abc/XYZ}"
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}
```
This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The `mv` at the end just moves the temporary file to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)
This uses a Bash-only [parameter expansion](https://www.gnu.org/s/bash/manual/html_node/Shell-Parameter-Expansion.html) to perform a replacement on the variable's value.
|
14352290
|
Listing only directories using ls in Bash?
| 1,354
|
2013-01-16 06:07:00
|
<p>This command lists directories in the current path:</p>
<pre class="lang-bash prettyprint-override"><code>ls -d */
</code></pre>
<p>What exactly does the pattern <code>*/</code> do?</p>
<p>And how can we give the absolute path in the above command (e.g. <code>ls -d /home/alice/Documents</code>) for listing only directories in that path?</p>
| 1,340,311
| 1,651,941
|
2025-06-11 13:18:12
| 14,352,330
| 1,384
|
2013-01-16 06:11:28
| 89,817
|
2013-01-16 06:11:28
|
https://stackoverflow.com/q/14352290
|
https://stackoverflow.com/a/14352330
|
<p><code>*/</code> is a pattern that matches all of the subdirectories in the current directory (<code>*</code> would match all files <em>and</em> subdirectories; the <code>/</code> restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use <code>ls -d /home/alice/Documents/*/</code></p>
|
<p><code>*/</code> is a pattern that matches all of the subdirectories in the current directory (<code>*</code> would match all files <em>and</em> subdirectories; the <code>/</code> restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use <code>ls -d /home/alice/Documents/*/</code></p>
|
218, 387, 3589
|
bash, directory, ls
|
<h1>Listing only directories using ls in Bash?</h1>
<p>This command lists directories in the current path:</p>
<pre class="lang-bash prettyprint-override"><code>ls -d */
</code></pre>
<p>What exactly does the pattern <code>*/</code> do?</p>
<p>And how can we give the absolute path in the above command (e.g. <code>ls -d /home/alice/Documents</code>) for listing only directories in that path?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 102
|
bash
|
# Listing only directories using ls in Bash?
This command lists directories in the current path:
```
ls -d */
```
What exactly does the pattern `*/` do?
And how can we give the absolute path in the above command (e.g. `ls -d /home/alice/Documents`) for listing only directories in that path?
|
`*/` is a pattern that matches all of the subdirectories in the current directory (`*` would match all files *and* subdirectories; the `/` restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use `ls -d /home/alice/Documents/*/`
|
2870992
|
Automatic exit from Bash shell script on error
| 867
|
2010-05-20 04:21:53
|
<p>I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:</p>
<pre><code>#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
</code></pre>
<p>So in this case, if the script can't change to the indicated directory, then it would certainly not want to do a <em>./configure</em> afterwards if it fails.</p>
<p>Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?</p>
| 472,962
| 341,133
|
2024-08-23 15:30:16
| 2,871,034
| 1,380
|
2010-05-20 04:36:01
| 9,530
|
2023-02-26 08:24:05
|
https://stackoverflow.com/q/2870992
|
https://stackoverflow.com/a/2871034
|
<p>Use the <a href="http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin" rel="noreferrer"><code>set -e</code></a> builtin:</p>
<pre><code>#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
</code></pre>
<p>Alternatively, you can pass <code>-e</code> on the command line:</p>
<pre><code>bash -e my_script.sh
</code></pre>
<p>You can also <strong>disable</strong> this behavior with <code>set +e</code>.</p>
<p>You may also want to employ all or some of the the <code>-e</code> <code>-u</code> <code>-x</code> and <code>-o pipefail</code> options like so:</p>
<pre><code>set -euxo pipefail
</code></pre>
<p><code>-e</code> exits on error, <code>-u</code> errors on undefined variables, <code>-x</code> prints commands before execution, and <code>-o (for option) pipefail</code> exits on command pipe failures. Some gotchas and workarounds are documented well <a href="https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/" rel="noreferrer">here</a>.</p>
<p>(*) Note:</p>
<blockquote>
<p>The shell does <em>not</em> exit if the command that fails is part of the
command list immediately following a <strong>while</strong> or <strong>until</strong> keyword,
part of the test following the <strong>if</strong> or <strong>elif</strong> reserved words, part
of any command executed in a <strong>&&</strong> or <strong>||</strong> list except the command
following the final <strong>&&</strong> or <strong>||</strong>, any command in a pipeline but
the last, or if the command's return value is being inverted with
<strong>!</strong></p>
</blockquote>
<p>(from <code>man bash</code>)</p>
|
<p>Use the <a href="http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin" rel="noreferrer"><code>set -e</code></a> builtin:</p> <pre><code>#!/bin/bash set -e # Any subsequent(*) commands which fail will cause the shell script to exit immediately </code></pre> <p>Alternatively, you can pass <code>-e</code> on the command line:</p> <pre><code>bash -e my_script.sh </code></pre> <p>You
|
379, 387, 390, 10871
|
bash, error-handling, exit, shell
|
<h1>Automatic exit from Bash shell script on error</h1>
<p>I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:</p>
<pre><code>#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
</code></pre>
<p>So in this case, if the script can't change to the indicated directory, then it would certainly not want to do a <em>./configure</em> afterwards if it fails.</p>
<p>Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 103
|
bash
|
# Automatic exit from Bash shell script on error
I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:
```
#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
```
So in this case, if the script can't change to the indicated directory, then it would certainly not want to do a *./configure* afterwards if it fails.
Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?
|
Use the [`set -e`](http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin) builtin:
```
#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
```
Alternatively, you can pass `-e` on the command line:
```
bash -e my_script.sh
```
You can also **disable** this behavior with `set +e`.
You may also want to employ all or some of the the `-e` `-u` `-x` and `-o pipefail` options like so:
```
set -euxo pipefail
```
`-e` exits on error, `-u` errors on undefined variables, `-x` prints commands before execution, and `-o (for option) pipefail` exits on command pipe failures. Some gotchas and workarounds are documented well [here](https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/).
(*) Note:
> The shell does *not* exit if the command that fails is part of the
> command list immediately following a **while** or **until** keyword,
> part of the test following the **if** or **elif** reserved words, part
> of any command executed in a **&&** or **||** list except the command
> following the final **&&** or **||**, any command in a pipeline but
> the last, or if the command's return value is being inverted with
> **!**
(from `man bash`)
|
604864
|
Print a file, skipping the first X lines, in Bash
| 838
|
2009-03-03 02:19:54
|
<p>I have a very long file which I want to print, skipping the first 1,000,000 lines, for example.</p>
<p>I looked into the cat man page, but I did not see any option to do this. I am looking for a command to do this or a simple Bash program.</p>
| 738,330
| 39,160
|
2023-08-02 00:59:46
| 604,871
| 1,378
|
2009-03-03 02:24:05
| 65,696
|
2023-08-02 00:59:46
|
https://stackoverflow.com/q/604864
|
https://stackoverflow.com/a/604871
|
<p>Use <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer"><code>tail</code></a>. Some examples:</p>
<pre><code>$ tail file.log
< Last 10 lines of file.log >
</code></pre>
<p>To SKIP the first N lines:</p>
<pre><code>$ tail -n +<N+1> <filename>
< filename, excluding first N lines. >
</code></pre>
<p>For instance, to skip the first 10 lines:</p>
<pre><code>$ tail -n +11 file.log
< file.log, starting at line 11, after skipping the first 10 lines. >
</code></pre>
<p>To see the last N lines, omit the "+":</p>
<pre><code>$ tail -n <N> <filename>
< last N lines of file. >
</code></pre>
|
<p>Use <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer"><code>tail</code></a>. Some examples:</p> <pre><code>$ tail file.log < Last 10 lines of file.log > </code></pre> <p>To SKIP the first N lines:</p> <pre><code>$ tail -n +<N+1> <filename> < filename, excluding first N lines. > </code></pre> <p>For instance, to skip the first 10 lines:</p> <pre
|
58, 87, 387, 5971
|
bash, linux, printing, skip
|
<h1>Print a file, skipping the first X lines, in Bash</h1>
<p>I have a very long file which I want to print, skipping the first 1,000,000 lines, for example.</p>
<p>I looked into the cat man page, but I did not see any option to do this. I am looking for a command to do this or a simple Bash program.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 104
|
bash
|
# Print a file, skipping the first X lines, in Bash
I have a very long file which I want to print, skipping the first 1,000,000 lines, for example.
I looked into the cat man page, but I did not see any option to do this. I am looking for a command to do this or a simple Bash program.
|
Use [`tail`](http://man7.org/linux/man-pages/man1/tail.1.html). Some examples:
```
$ tail file.log
< Last 10 lines of file.log >
```
To SKIP the first N lines:
```
$ tail -n +<N+1> <filename>
< filename, excluding first N lines. >
```
For instance, to skip the first 10 lines:
```
$ tail -n +11 file.log
< file.log, starting at line 11, after skipping the first 10 lines. >
```
To see the last N lines, omit the "+":
```
$ tail -n <N> <filename>
< last N lines of file. >
```
|
2198377
|
How can I clear previous output in Terminal in Mac OS X?
| 710
|
2010-02-04 09:00:45
|
<p>I know the <code>clear</code> command that 'clears' the current screen, but it does this just by printing lots of newlines - the cleared contents just get scrolled up.</p>
<p>Is there a way to completely wipe all previous output from the terminal so that I can't reach it even by scrolling up?</p>
| 382,826
| 246,776
|
2025-08-11 02:46:12
| 2,198,403
| 1,367
|
2010-02-04 09:04:24
| 226,621
|
2017-04-20 03:13:50
|
https://stackoverflow.com/q/2198377
|
https://stackoverflow.com/a/2198403
|
<h3>To clear the terminal manually:</h3>
<p><kbd>⌘</kbd>+<kbd>K</kbd></p>
<p><kbd>Command</kbd>+<kbd>K</kbd> for newer keyboards</p>
<h3>To clear the terminal from within a shell script;</h3>
<pre><code>/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
</code></pre>
|
<h3>To clear the terminal manually:</h3> <p><kbd>⌘</kbd>+<kbd>K</kbd></p> <p><kbd>Command</kbd>+<kbd>K</kbd> for newer keyboards</p> <h3>To clear the terminal from within a shell script;</h3> <pre><code>/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down' </code></pre>
|
369, 390, 1390
|
buffer, macos, shell
|
<h1>How can I clear previous output in Terminal in Mac OS X?</h1>
<p>I know the <code>clear</code> command that 'clears' the current screen, but it does this just by printing lots of newlines - the cleared contents just get scrolled up.</p>
<p>Is there a way to completely wipe all previous output from the terminal so that I can't reach it even by scrolling up?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 105
|
bash
|
# How can I clear previous output in Terminal in Mac OS X?
I know the `clear` command that 'clears' the current screen, but it does this just by printing lots of newlines - the cleared contents just get scrolled up.
Is there a way to completely wipe all previous output from the terminal so that I can't reach it even by scrolling up?
|
### To clear the terminal manually:
`⌘`+`K`
`Command`+`K` for newer keyboards
### To clear the terminal from within a shell script;
```
/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
```
|
14654718
|
How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"
| 827
|
2013-02-01 20:46:47
|
<pre><code>$ adb --help
</code></pre>
<hr />
<pre><code>-s SERIAL use device with given serial (overrides $ANDROID_SERIAL)
</code></pre>
<hr />
<pre><code>$ adb devices
List of devices attached
emulator-5554 device
7f1c864e device
</code></pre>
<hr />
<pre><code>$ adb shell -s 7f1c864e
error: more than one device and emulator
</code></pre>
| 865,641
| 125,212
|
2024-06-12 13:16:22
| 14,655,015
| 1,366
|
2013-02-01 21:04:25
| 1,548,085
|
2022-11-15 04:21:46
|
https://stackoverflow.com/q/14654718
|
https://stackoverflow.com/a/14655015
|
<p>Use the <code>-s</code> option BEFORE the command to specify the device, for example:</p>
<pre><code>adb -s 7f1c864e shell
</code></pre>
<p>For multiple Emulator, use the process's IP and port as the id, like:</p>
<pre><code>adb -s 192.168.232.2:5555 <command>
</code></pre>
<blockquote>
<p>See <a href="https://stackoverflow.com/q/1720346/8740349">How to get the Android Emulator's IP address?</a></p>
<p>But if there is only a single Emulator, try:</p>
<pre><code>adb -e <command>
</code></pre>
</blockquote>
<p>See also <a href="http://developer.android.com/tools/help/adb.html#directingcommands" rel="noreferrer">http://developer.android.com/tools/help/adb.html#directingcommands</a></p>
|
<p>Use the <code>-s</code> option BEFORE the command to specify the device, for example:</p> <pre><code>adb -s 7f1c864e shell </code></pre> <p>For multiple Emulator, use the process's IP and port as the id, like:</p> <pre><code>adb -s 192.168.232.2:5555 <command> </code></pre> <blockquote> <p>See <a href="https://stackoverflow.com/q/1720346/8740349">How to get the Android Emulator's IP addre
|
390, 1386, 2631, 22975, 87183
|
adb, android, android-debug, cmd, shell
|
<h1>How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"</h1>
<pre><code>$ adb --help
</code></pre>
<hr />
<pre><code>-s SERIAL use device with given serial (overrides $ANDROID_SERIAL)
</code></pre>
<hr />
<pre><code>$ adb devices
List of devices attached
emulator-5554 device
7f1c864e device
</code></pre>
<hr />
<pre><code>$ adb shell -s 7f1c864e
error: more than one device and emulator
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 106
|
bash
|
# How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"
```
$ adb --help
```
---
```
-s SERIAL use device with given serial (overrides $ANDROID_SERIAL)
```
---
```
$ adb devices
List of devices attached
emulator-5554 device
7f1c864e device
```
---
```
$ adb shell -s 7f1c864e
error: more than one device and emulator
```
|
Use the `-s` option BEFORE the command to specify the device, for example:
```
adb -s 7f1c864e shell
```
For multiple Emulator, use the process's IP and port as the id, like:
```
adb -s 192.168.232.2:5555 <command>
```
> See [How to get the Android Emulator's IP address?](https://stackoverflow.com/q/1720346/8740349)
>
> But if there is only a single Emulator, try:
>
> ```
> adb -e <command>
> ```
See also <http://developer.android.com/tools/help/adb.html#directingcommands>
|
613572
|
Capturing multiple line output into a Bash variable
| 715
|
2009-03-05 04:32:18
|
<p>I've got a script 'myscript' that outputs the following:</p>
<pre><code>abc
def
ghi
</code></pre>
<p>in another script, I call:</p>
<pre><code>declare RESULT=$(./myscript)
</code></pre>
<p>and <code>$RESULT</code> gets the value</p>
<pre><code>abc def ghi
</code></pre>
<p>Is there a way to store the result either with the newlines, or with '\n' character so I can output it with '<code>echo -e</code>'?</p>
| 380,409
| 42,562
|
2024-04-09 06:00:01
| 613,580
| 1,326
|
2009-03-05 04:36:09
| 15,168
|
2014-08-04 20:33:02
|
https://stackoverflow.com/q/613572
|
https://stackoverflow.com/a/613580
|
<p>Actually, RESULT contains what you want — to demonstrate:</p>
<pre><code>echo "$RESULT"
</code></pre>
<p>What you show is what you get from:</p>
<pre><code>echo $RESULT
</code></pre>
<hr>
<p>As noted in the comments, the difference is that (1) the double-quoted version of the variable (<code>echo "$RESULT"</code>) preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (<code>echo $RESULT</code>) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).</p>
|
<p>Actually, RESULT contains what you want — to demonstrate:</p> <pre><code>echo "$RESULT" </code></pre> <p>What you show is what you get from:</p> <pre><code>echo $RESULT </code></pre> <hr> <p>As noted in the comments, the difference is that (1) the double-quoted version of the variable (<code>echo "$RESULT"</code>) preserves internal spacing of the value exactly as it is represented in the
|
276, 387
|
bash, variables
|
<h1>Capturing multiple line output into a Bash variable</h1>
<p>I've got a script 'myscript' that outputs the following:</p>
<pre><code>abc
def
ghi
</code></pre>
<p>in another script, I call:</p>
<pre><code>declare RESULT=$(./myscript)
</code></pre>
<p>and <code>$RESULT</code> gets the value</p>
<pre><code>abc def ghi
</code></pre>
<p>Is there a way to store the result either with the newlines, or with '\n' character so I can output it with '<code>echo -e</code>'?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 107
|
bash
|
# Capturing multiple line output into a Bash variable
I've got a script 'myscript' that outputs the following:
```
abc
def
ghi
```
in another script, I call:
```
declare RESULT=$(./myscript)
```
and `$RESULT` gets the value
```
abc def ghi
```
Is there a way to store the result either with the newlines, or with '\n' character so I can output it with '`echo -e`'?
|
Actually, RESULT contains what you want — to demonstrate:
```
echo "$RESULT"
```
What you show is what you get from:
```
echo $RESULT
```
---
As noted in the comments, the difference is that (1) the double-quoted version of the variable (`echo "$RESULT"`) preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (`echo $RESULT`) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).
|
11231937
|
Bash ignoring error for a particular command
| 814
|
2012-06-27 17:34:55
|
<p>I am using following options</p>
<pre><code>set -o pipefail
set -e
</code></pre>
<p>In bash script to stop execution on error. I have ~100 lines of script executing and I don't want to check return code of every line in the script. </p>
<p>But for one particular command, I want to ignore the error. How can I do that?</p>
| 656,101
| 428,705
|
2024-11-08 05:07:51
| 11,231,970
| 1,319
|
2012-06-27 17:37:44
| 1,458,569
|
2019-11-19 07:47:38
|
https://stackoverflow.com/q/11231937
|
https://stackoverflow.com/a/11231970
|
<p>The solution:</p>
<pre><code>particular_script || true
</code></pre>
<p>Example:</p>
<pre><code>$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo one
particular_script || true
echo two
particular_script
echo three
$ bash /tmp/1.sh
one
two
</code></pre>
<p><code>three</code> will be never printed.</p>
<p>Also, I want to add that when <code>pipefail</code> is on,
it is enough for shell to think that the entire pipe has non-zero exit code
when one of commands in the pipe has non-zero exit code (with <code>pipefail</code> off it must the last one).</p>
<pre><code>$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
</code></pre>
|
<p>The solution:</p> <pre><code>particular_script || true </code></pre> <p>Example:</p> <pre><code>$ cat /tmp/1.sh particular_script() { false } set -e echo one particular_script || true echo two particular_script echo three $ bash /tmp/1.sh one two </code></pre> <p><code>three</code> will be never printed.</p> <p>Also, I want to add that when <code>pipefail</code> is on, it is enough
|
58, 387
|
bash, linux
|
<h1>Bash ignoring error for a particular command</h1>
<p>I am using following options</p>
<pre><code>set -o pipefail
set -e
</code></pre>
<p>In bash script to stop execution on error. I have ~100 lines of script executing and I don't want to check return code of every line in the script. </p>
<p>But for one particular command, I want to ignore the error. How can I do that?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 108
|
bash
|
# Bash ignoring error for a particular command
I am using following options
```
set -o pipefail
set -e
```
In bash script to stop execution on error. I have ~100 lines of script executing and I don't want to check return code of every line in the script.
But for one particular command, I want to ignore the error. How can I do that?
|
The solution:
```
particular_script || true
```
Example:
```
$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo one
particular_script || true
echo two
particular_script
echo three
$ bash /tmp/1.sh
one
two
```
`three` will be never printed.
Also, I want to add that when `pipefail` is on,
it is enough for shell to think that the entire pipe has non-zero exit code
when one of commands in the pipe has non-zero exit code (with `pipefail` off it must the last one).
```
$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
```
|
785519
|
How do I remove all .pyc files from a project?
| 749
|
2009-04-24 11:51:39
|
<p>I've renamed some files in a fairly large project and want to remove the .pyc files they've left behind. I tried the bash script:</p>
<pre><code> rm -r *.pyc
</code></pre>
<p>But that doesn't recurse through the folders as I thought it would. What am I doing wrong?</p>
| 387,358
| 1,384,652
|
2024-03-03 19:27:27
| 785,534
| 1,304
|
2009-04-24 11:55:27
| 1,288
|
2018-07-17 09:27:03
|
https://stackoverflow.com/q/785519
|
https://stackoverflow.com/a/785534
|
<pre><code>find . -name "*.pyc" -exec rm -f {} \;
</code></pre>
|
<pre><code>find . -name "*.pyc" -exec rm -f {} \; </code></pre>
|
387
|
bash
|
<h1>How do I remove all .pyc files from a project?</h1>
<p>I've renamed some files in a fairly large project and want to remove the .pyc files they've left behind. I tried the bash script:</p>
<pre><code> rm -r *.pyc
</code></pre>
<p>But that doesn't recurse through the folders as I thought it would. What am I doing wrong?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 109
|
bash
|
# How do I remove all .pyc files from a project?
I've renamed some files in a fairly large project and want to remove the .pyc files they've left behind. I tried the bash script:
```
rm -r *.pyc
```
But that doesn't recurse through the folders as I thought it would. What am I doing wrong?
|
```
find . -name "*.pyc" -exec rm -f {} \;
```
|
16623835
|
Remove a fixed prefix/suffix from a string in Bash
| 849
|
2013-05-18 11:37:50
|
<p>I want to remove the prefix/suffix from a string. For example, given:</p>
<pre><code>string="hello-world"
prefix="hell"
suffix="ld"
</code></pre>
<p>How do I get the following result?</p>
<pre><code>"o-wor"
</code></pre>
| 840,768
| 1,103,412
|
2023-10-06 12:42:22
| 16,623,897
| 1,293
|
2013-05-18 11:43:59
| 612,462
|
2022-03-14 18:25:08
|
https://stackoverflow.com/q/16623835
|
https://stackoverflow.com/a/16623897
|
<pre><code>$ prefix="hell"
$ suffix="ld"
$ string="hello-world"
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
</code></pre>
<p>This is documented in the <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Shell Parameter Expansion</a> section of the manual:</p>
<blockquote>
<p><code>${parameter#word}</code><br />
<code>${parameter##word}</code></p>
<p>The word is expanded to produce a pattern and matched according to the rules described below (see <a href="https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html" rel="noreferrer">Pattern Matching</a>). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the <code>#</code> case) or the longest matching pattern (the <code>##</code> case) deleted. […]</p>
<p><code>${parameter%word}</code><br />
<code>${parameter%%word}</code></p>
<p>The word is expanded to produce a pattern and matched according to the rules described below (see <a href="https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html" rel="noreferrer">Pattern Matching</a>). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the <code>%</code> case) or the longest matching pattern (the <code>%%</code> case) deleted. […]</p>
</blockquote>
|
<pre><code>$ prefix="hell" $ suffix="ld" $ string="hello-world" $ foo=${string#"$prefix"} $ foo=${foo%"$suffix"} $ echo "${foo}" o-wor </code></pre> <p>This is documented in the <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Shell Parameter Expansion</a> section of the manual:<
|
387, 2498, 12282, 25968
|
bash, pattern-matching, replace, string-interpolation
|
<h1>Remove a fixed prefix/suffix from a string in Bash</h1>
<p>I want to remove the prefix/suffix from a string. For example, given:</p>
<pre><code>string="hello-world"
prefix="hell"
suffix="ld"
</code></pre>
<p>How do I get the following result?</p>
<pre><code>"o-wor"
</code></pre>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 110
|
bash
|
# Remove a fixed prefix/suffix from a string in Bash
I want to remove the prefix/suffix from a string. For example, given:
```
string="hello-world"
prefix="hell"
suffix="ld"
```
How do I get the following result?
```
"o-wor"
```
|
```
$ prefix="hell"
$ suffix="ld"
$ string="hello-world"
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
```
This is documented in the [Shell Parameter Expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) section of the manual:
> `${parameter#word}`
> `${parameter##word}`
>
> The word is expanded to produce a pattern and matched according to the rules described below (see [Pattern Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the `#` case) or the longest matching pattern (the `##` case) deleted. […]
>
> `${parameter%word}`
> `${parameter%%word}`
>
> The word is expanded to produce a pattern and matched according to the rules described below (see [Pattern Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the `%` case) or the longest matching pattern (the `%%` case) deleted. […]
|
2268104
|
Command not found error in Bash variable assignment
| 729
|
2010-02-15 18:32:30
|
<p>I have this script called test.sh:</p>
<pre><code>#!/bin/bash
STR = "Hello World"
echo $STR
</code></pre>
<p>when I run <code>sh test.sh</code> I get this:</p>
<pre><code>test.sh: line 2: STR: command not found
</code></pre>
<p>What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.</p>
<p>I'm on Ubuntu Server 9.10. And yes, bash is located at <code>/bin/bash</code>.</p>
| 481,341
| 172,350
|
2023-10-20 00:42:27
| 2,268,117
| 1,263
|
2010-02-15 18:34:40
| 140,750
|
2021-01-29 13:15:59
|
https://stackoverflow.com/q/2268104
|
https://stackoverflow.com/a/2268117
|
<p>You cannot have spaces around the <code>=</code> sign.</p>
<p>When you write:</p>
<pre><code>STR = "foo"
</code></pre>
<p>bash tries to run a command named <code>STR</code> with 2 arguments (the strings <code>=</code> and <code>foo</code>)</p>
<p>When you write:</p>
<pre><code>STR =foo
</code></pre>
<p>bash tries to run a command named <code>STR</code> with 1 argument (the string <code>=foo</code>)</p>
<p>When you write:</p>
<pre><code>STR= foo
</code></pre>
<p>bash tries to run the command <code>foo</code> with STR set to the empty string in its environment.</p>
<p>I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:</p>
<ol>
<li>the first command is exactly equivalent to: <code>STR "=" "foo"</code>,</li>
<li>the second is the same as <code>STR "=foo"</code>,</li>
<li>and the last is equivalent to <code>STR="" foo</code>.</li>
</ol>
<p>The relevant section of the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01" rel="noreferrer">sh language spec, section 2.9.1</a> states:</p>
<blockquote>
<p>A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.</p>
</blockquote>
<p>In that context, a <code>word</code> is the command that bash is going to run. Any string containing <code>=</code> (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the <code>=</code> is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In <code>STR = "foo"</code>, <code>STR</code> is not a variable assignment.</p>
|
<p>You cannot have spaces around the <code>=</code> sign.</p> <p>When you write:</p> <pre><code>STR = "foo" </code></pre> <p>bash tries to run a command named <code>STR</code> with 2 arguments (the strings <code>=</code> and <code>foo</code>)</p> <p>When you write:</p> <pre><code>STR =foo </code></pre> <p>bash tries to run a command named <code>STR</code> with 1 argument (the string <cod
|
367, 387, 390, 10327, 14036
|
bash, sh, shell, syntax, variable-assignment
|
<h1>Command not found error in Bash variable assignment</h1>
<p>I have this script called test.sh:</p>
<pre><code>#!/bin/bash
STR = "Hello World"
echo $STR
</code></pre>
<p>when I run <code>sh test.sh</code> I get this:</p>
<pre><code>test.sh: line 2: STR: command not found
</code></pre>
<p>What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.</p>
<p>I'm on Ubuntu Server 9.10. And yes, bash is located at <code>/bin/bash</code>.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 111
|
bash
|
# Command not found error in Bash variable assignment
I have this script called test.sh:
```
#!/bin/bash
STR = "Hello World"
echo $STR
```
when I run `sh test.sh` I get this:
```
test.sh: line 2: STR: command not found
```
What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.
I'm on Ubuntu Server 9.10. And yes, bash is located at `/bin/bash`.
|
You cannot have spaces around the `=` sign.
When you write:
```
STR = "foo"
```
bash tries to run a command named `STR` with 2 arguments (the strings `=` and `foo`)
When you write:
```
STR =foo
```
bash tries to run a command named `STR` with 1 argument (the string `=foo`)
When you write:
```
STR= foo
```
bash tries to run the command `foo` with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
1. the first command is exactly equivalent to: `STR "=" "foo"`,
2. the second is the same as `STR "=foo"`,
3. and the last is equivalent to `STR="" foo`.
The relevant section of the [sh language spec, section 2.9.1](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01) states:
> A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a `word` is the command that bash is going to run. Any string containing `=` (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the `=` is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In `STR = "foo"`, `STR` is not a variable assignment.
|
4277665
|
How do I compare two string variables in an 'if' statement in Bash?
| 891
|
2010-11-25 13:39:33
|
<p>I'm trying to get an <code>if</code> statement to work in <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> (using <a href="http://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="noreferrer">Ubuntu</a>):</p>
<pre><code>#!/bin/bash
s1="hi"
s2="hi"
if ["$s1" == "$s2"]
then
echo match
fi
</code></pre>
<p>I've tried various forms of the <code>if</code> statement, using <code>[["$s1" == "$s2"]]</code>, with and without quotes, using <code>=</code>, <code>==</code> and <code>-eq</code>, but I still get the following error:</p>
<blockquote>
<p>[hi: command not found</p>
</blockquote>
<p>I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?</p>
<p>Eventually, I want to say if <code>$s1</code> contains <code>$s2</code>, so how can I do that?</p>
<p>I did just work out the spaces bit... :/ How do I say <em>contains</em>?</p>
<p>I tried</p>
<pre><code>if [[ "$s1" == "*$s2*" ]]
</code></pre>
<p>but it didn't work.</p>
| 1,652,836
| 198,048
|
2021-02-15 01:47:03
| 4,277,753
| 1,259
|
2010-11-25 13:49:49
| 89,806
|
2020-06-15 13:30:01
|
https://stackoverflow.com/q/4277665
|
https://stackoverflow.com/a/4277753
|
<p>For string equality comparison, use:</p>
<pre><code>if [[ "$s1" == "$s2" ]]
</code></pre>
<p>For string does NOT equal comparison, use:</p>
<pre><code>if [[ "$s1" != "$s2" ]]
</code></pre>
<p>For the <code>a</code> contains <code>b</code>, use:</p>
<pre><code>if [[ $s1 == *"$s2"* ]]
</code></pre>
<p>(and make sure to add spaces between the symbols):</p>
<p>Bad:</p>
<pre><code>if [["$s1" == "$s2"]]
</code></pre>
<p>Good:</p>
<pre><code>if [[ "$s1" == "$s2" ]]
</code></pre>
|
<p>For string equality comparison, use:</p> <pre><code>if [[ "$s1" == "$s2" ]] </code></pre> <p>For string does NOT equal comparison, use:</p> <pre><code>if [[ "$s1" != "$s2" ]] </code></pre> <p>For the <code>a</code> contains <code>b</code>, use:</p> <pre><code>if [[ $s1 == *"$s2"* ]] </code></pre> <p>(and make sure to add spaces between the symbols):</p> <p>Bad:</p> <pre><code>if [["$s1"
|
387, 531, 2773
|
bash, if-statement, scripting
|
<h1>How do I compare two string variables in an 'if' statement in Bash?</h1>
<p>I'm trying to get an <code>if</code> statement to work in <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> (using <a href="http://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="noreferrer">Ubuntu</a>):</p>
<pre><code>#!/bin/bash
s1="hi"
s2="hi"
if ["$s1" == "$s2"]
then
echo match
fi
</code></pre>
<p>I've tried various forms of the <code>if</code> statement, using <code>[["$s1" == "$s2"]]</code>, with and without quotes, using <code>=</code>, <code>==</code> and <code>-eq</code>, but I still get the following error:</p>
<blockquote>
<p>[hi: command not found</p>
</blockquote>
<p>I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?</p>
<p>Eventually, I want to say if <code>$s1</code> contains <code>$s2</code>, so how can I do that?</p>
<p>I did just work out the spaces bit... :/ How do I say <em>contains</em>?</p>
<p>I tried</p>
<pre><code>if [[ "$s1" == "*$s2*" ]]
</code></pre>
<p>but it didn't work.</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 112
|
bash
|
# How do I compare two string variables in an 'if' statement in Bash?
I'm trying to get an `if` statement to work in [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) (using [Ubuntu](http://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29)):
```
#!/bin/bash
s1="hi"
s2="hi"
if ["$s1" == "$s2"]
then
echo match
fi
```
I've tried various forms of the `if` statement, using `[["$s1" == "$s2"]]`, with and without quotes, using `=`, `==` and `-eq`, but I still get the following error:
> [hi: command not found
I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?
Eventually, I want to say if `$s1` contains `$s2`, so how can I do that?
I did just work out the spaces bit... :/ How do I say *contains*?
I tried
```
if [[ "$s1" == "*$s2*" ]]
```
but it didn't work.
|
For string equality comparison, use:
```
if [[ "$s1" == "$s2" ]]
```
For string does NOT equal comparison, use:
```
if [[ "$s1" != "$s2" ]]
```
For the `a` contains `b`, use:
```
if [[ $s1 == *"$s2"* ]]
```
(and make sure to add spaces between the symbols):
Bad:
```
if [["$s1" == "$s2"]]
```
Good:
```
if [[ "$s1" == "$s2" ]]
```
|
273743
|
Using wget to recursively fetch a directory with arbitrary files in it
| 707
|
2008-11-07 21:44:26
|
<p>I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:</p>
<pre><code>http://mysite.com/configs/.vim/
</code></pre>
<p>.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?</p>
| 1,131,842
| 2,476
|
2025-03-18 22:32:09
| 273,776
| 1,227
|
2008-11-07 21:55:41
| 813
|
2017-10-04 21:53:13
|
https://stackoverflow.com/q/273743
|
https://stackoverflow.com/a/273776
|
<p>You have to pass the <code>-np</code>/<code>--no-parent</code> option to <code>wget</code> (in addition to <code>-r</code>/<code>--recursive</code>, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:</p>
<pre><code>wget --recursive --no-parent http://example.com/configs/.vim/
</code></pre>
<p>To avoid downloading the auto-generated <code>index.html</code> files, use the <code>-R</code>/<code>--reject</code> option:</p>
<pre><code>wget -r -np -R "index.html*" http://example.com/configs/.vim/
</code></pre>
|
<p>You have to pass the <code>-np</code>/<code>--no-parent</code> option to <code>wget</code> (in addition to <code>-r</code>/<code>--recursive</code>, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:</p> <pre><code>wget --recursive --no-parent http://example.com/configs/.vim/ </code></pre> <p>To avoid d
|
390, 5583
|
shell, wget
|
<h1>Using wget to recursively fetch a directory with arbitrary files in it</h1>
<p>I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:</p>
<pre><code>http://mysite.com/configs/.vim/
</code></pre>
<p>.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 113
|
bash
|
# Using wget to recursively fetch a directory with arbitrary files in it
I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:
```
http://mysite.com/configs/.vim/
```
.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?
|
You have to pass the `-np`/`--no-parent` option to `wget` (in addition to `-r`/`--recursive`, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:
```
wget --recursive --no-parent http://example.com/configs/.vim/
```
To avoid downloading the auto-generated `index.html` files, use the `-R`/`--reject` option:
```
wget -r -np -R "index.html*" http://example.com/configs/.vim/
```
|
5466329
|
What's the best way to determine the location of the current PowerShell script?
| 763
|
2011-03-28 23:46:30
|
<p>Whenever I need to reference a common module or script, I like to use paths relative to the current script file. That way, my script can always find other scripts in the library.</p>
<p>So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:</p>
<pre><code>$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
</code></pre>
<p>I know in modules (.psm1) you can use <code>$PSScriptRoot</code> to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).</p>
<p><strong>What's the canonical way to get the current PowerShell script file's location?</strong></p>
| 873,175
| 125,356
|
2023-02-11 08:42:59
| 5,466,355
| 1,224
|
2011-03-28 23:50:08
| 23,283
|
2019-10-21 23:01:32
|
https://stackoverflow.com/q/5466329
|
https://stackoverflow.com/a/5466355
|
<p><a href="https://stackoverflow.com/a/5467533"><strong>PowerShell 3+</strong></a></p>
<pre class="lang-sh prettyprint-override"><code># This is an automatic variable set to the current file's/module's directory
$PSScriptRoot
</code></pre>
<p><strong>PowerShell 2</strong></p>
<p>Prior to PowerShell 3, there was not a better way than querying the
<code>MyInvocation.MyCommand.Definition</code> property for general scripts. I had the following line at the top of essentially every PowerShell script I had:</p>
<pre><code>$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
</code></pre>
|
<p><a href="https://stackoverflow.com/a/5467533"><strong>PowerShell 3+</strong></a></p> <pre class="lang-sh prettyprint-override"><code># This is an automatic variable set to the current file's/module's directory $PSScriptRoot </code></pre> <p><strong>PowerShell 2</strong></p> <p>Prior to PowerShell 3, there was not a better way than querying the <code>MyInvocation.MyCommand.Definition</code> p
|
526, 24067
|
powershell, powershell-2.0
|
<h1>What's the best way to determine the location of the current PowerShell script?</h1>
<p>Whenever I need to reference a common module or script, I like to use paths relative to the current script file. That way, my script can always find other scripts in the library.</p>
<p>So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:</p>
<pre><code>$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
</code></pre>
<p>I know in modules (.psm1) you can use <code>$PSScriptRoot</code> to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).</p>
<p><strong>What's the canonical way to get the current PowerShell script file's location?</strong></p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 114
|
bash
|
# What's the best way to determine the location of the current PowerShell script?
Whenever I need to reference a common module or script, I like to use paths relative to the current script file. That way, my script can always find other scripts in the library.
So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:
```
$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
```
I know in modules (.psm1) you can use `$PSScriptRoot` to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).
**What's the canonical way to get the current PowerShell script file's location?**
|
[**PowerShell 3+**](https://stackoverflow.com/a/5467533)
```
# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot
```
**PowerShell 2**
Prior to PowerShell 3, there was not a better way than querying the
`MyInvocation.MyCommand.Definition` property for general scripts. I had the following line at the top of essentially every PowerShell script I had:
```
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
```
|
4585929
|
How to use 'cp' command to exclude a specific directory?
| 703
|
2011-01-03 15:53:52
|
<p>I want to copy all files in a directory except some files in a specific sub-directory.
I have noticed that <code>cp</code> command didn't have the <code>--exclude</code> option.
So, how can I achieve this?</p>
| 797,279
| 554,241
|
2023-05-23 20:11:50
| 14,789,400
| 1,217
|
2013-02-09 15:04:45
| 2,057,305
|
2021-03-13 12:10:12
|
https://stackoverflow.com/q/4585929
|
https://stackoverflow.com/a/14789400
|
<p><code>rsync</code> is fast and easy:</p>
<pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude
</code></pre>
<p>You can use <code>--exclude</code> multiples times.</p>
<pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude
</code></pre>
<p><strong>Note that the dir <code>thefoldertoexclude</code> after <code>--exclude</code> option is relative to the <code>sourcefolder</code>, i.e., <code>sourcefolder/thefoldertoexclude</code>.</strong></p>
<p>Also you can add <code>-n</code> for dry run to see what will be copied before performing real operation, and if everything is ok, remove <code>-n</code> from command line.</p>
|
<p><code>rsync</code> is fast and easy:</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude </code></pre> <p>You can use <code>--exclude</code> multiples times.</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude </code></pre> <p><strong>Note that the dir <code>thefoldertoexcl
|
58, 387, 391, 1796, 25299
|
bash, command, cp, linux, terminal
|
<h1>How to use 'cp' command to exclude a specific directory?</h1>
<p>I want to copy all files in a directory except some files in a specific sub-directory.
I have noticed that <code>cp</code> command didn't have the <code>--exclude</code> option.
So, how can I achieve this?</p>
|
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
| 115
|
bash
|
# How to use 'cp' command to exclude a specific directory?
I want to copy all files in a directory except some files in a specific sub-directory.
I have noticed that `cp` command didn't have the `--exclude` option.
So, how can I achieve this?
|
`rsync` is fast and easy:
```
rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude
```
You can use `--exclude` multiples times.
```
rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude
```
**Note that the dir `thefoldertoexclude` after `--exclude` option is relative to the `sourcefolder`, i.e., `sourcefolder/thefoldertoexclude`.**
Also you can add `-n` for dry run to see what will be copied before performing real operation, and if everything is ok, remove `-n` from command line.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.