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 th... | 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 ... | <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 ... | 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... | 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 ... | ```
#!/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 ... |
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/li... | <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/li... | 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 ... | 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... |
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>... | <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>... | 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, s... |
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.o... | <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.o... | 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 out... |
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... | 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>??<... | 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 n... | <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 n... | 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
e... | 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';... | 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... |
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 exis... | 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>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> ... | 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... | 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 direct... | 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... |
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... | <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... | 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-in... |
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 mul... | 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 shoul... | <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 shoul... | 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 becau... | 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 `.`... | 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##*/}"
```
Yo... |
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>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 :<... | 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 t... | <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 t... | 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 host... |
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 (o... | 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... | <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... | 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 th... | 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 ... | #### 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"
... |
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
</cod... | 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>std... | <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>std... | 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++... | 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 *... |
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 cla... | 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>Admini... | <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>Admini... | 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 di... | 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-Execut... | 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 t... |
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 w... | <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 w... | 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 ... |
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... | <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... | 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]}", "${a... |
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 ... | <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 ... | 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 str... |
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>... | <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>... | 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 ... | 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 i... |
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 subdire... | 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... | <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... | 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... | 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 gi... | **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 whatev... |
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... | 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... | <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... | 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... | 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 ... | 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 "${MUL... |
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... | <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... | 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 ... | 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 int... |
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!... | 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 concern... | <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 concern... | 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>... | 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: sy... | 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=... |
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 wo... | 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"
}... | <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" }... | 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"
... | 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 multitud... | 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 ... |
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>... | 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>"... | <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>"... | 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></... | 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 fi... | ```
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... |
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, s... | 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... | <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... | 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
... | 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 recal... | 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 'defau... |
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 ... | 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 < <fil... | <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 < <fil... | 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.0... | 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 ... | 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.t... |
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}; d... | 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-E... | 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)):
```
f... | ```
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 da... | <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 da... | 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 c... |
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 myBackupFunct... | 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" "$a... | <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" "$a... | 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("..", "...... | 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,... | 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 b... |
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"}"
# 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"}" # p... | 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=... | 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}... |
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 stdou... | 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... | <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... | 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 o... | 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>&... |
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 ab... | 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... | 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 ... | 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 <s... | <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 <s... | 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 [Bas... |
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
c... | <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 c... | 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]*... |
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 d... | 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 ec... | <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 ec... | 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>... | 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 wi... | 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
$ ./... |
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 fi... | 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 t... | <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 t... | 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... | 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 ... | 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=... | 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'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# ... | <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'"'" # ^^^^^ ^^^^^ ^^^^^ ^^^^ # ... | 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></... | 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 ... | 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
```
... |
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... | <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... | 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 ... |
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>Fo... | 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... | <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... | 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 ... | 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 ... | 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'
```
`che... |
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'... | <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'... | 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>
</bloc... | 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/ma... |
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 ... | 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 d... | <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 d... | 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>... | 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 d... | 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 overri... |
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#ss1... | <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#ss1... | 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:... |
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... | <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... | 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 mult... |
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 cor... | 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.c... | <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.c... | 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... | 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 usi... | **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 interestin... |
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 fro... | 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... | <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... | 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 i... | 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` = "... | 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 lea... |
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><co... | 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/... | <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/... | 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 i... | 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:
```
% ...
... | 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 wi... |
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>
<... | 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). T... | <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). T... | 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 arg... | 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 h... | 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 ... |
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
[~]$ k... | 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 pro... | <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 pro... | 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 809... | 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... | 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]`... |
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... | 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>re... | <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>re... | 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... | 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... | 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 th... |
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.gi... | 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 <stro... | <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 <stro... | 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... | 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: pr... | 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 a... |
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:</... | 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 loca... | <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 loca... | 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 fi... | 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 fo... | 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 ... |
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... | 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 op... | <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 op... | 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/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/torn... | 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 edi... |
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... | 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 ...}... | <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 ...}... | 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... | 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... | - `$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 o... |
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
&... | <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 &... | 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> ... |
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> refor... | 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>p... | <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>p... | 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 ... | 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 lin... | 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",... |
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
</cod... | 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-file... | <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-file... | 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... | 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" o... | 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" (wildc... | <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" (wildc... | 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 e... | 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 w... | 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 ... |
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 'so... | 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.o... | <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.o... | 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... | 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 th... | 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#Redire... |
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>... | <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>... | 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 runni... |
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><... | 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 ... | <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 ... | 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... | 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 examp... | 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:
```
... |
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></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>
... | <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> ... | 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 &l... | 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------... | 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 consid... |
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 tha... | 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 ... | <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 ... | 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 <fil... | 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 ... | 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 QN... |
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 t... | 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-o... | <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-o... | 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 paramete... | 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 unknow... | 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 d... |
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>
... | 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, empt... | <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, empt... | 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] = Pa... | 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 ... | ```
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 appear... |
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 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... | <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... | 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>
<pr... | 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 ... | `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... |
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.... | <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.... | 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 wan... | 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... |
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 Do... | <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 Do... | 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 f... |
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 thi... | 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 ... | <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 ... | 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... | 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 correspond... | 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/ ... |
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 ... | 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... | 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>
<... | <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> <... | 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... | 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... | 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 operator... |
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 --exclu... | 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>... | 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 soluti... | 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> ... | <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> ... | 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 ... |
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 c... | <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 c... | 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 ca... |
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... | <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... | 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 th... |
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>. (N... | <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>. (N... | 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 w... |
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 ... | <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 ... | 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 ... | 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 who... |
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">... | 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 "... | 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 | j... | 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 ... | <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 ... | 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 ... |
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-o... | <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-o... | 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: prodmon... |
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 w... | 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</cod... | <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</cod... | 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 comman... | 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... | 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 B... |
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 dire... | 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/*/<... | <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/*/<... | 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... | 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 sc... | 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</cod... | <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</cod... | 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
... | 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
```
S... | 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 **disab... |
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... | <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... | 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,... |
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... | <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... | 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 t... | 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 ... | ### 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 devic... | 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:/... | <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:/... | 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
emu... | 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
```
---
... | 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... |
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 eit... | 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"</cod... | <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"</cod... | 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... | 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 ... | 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 re... |
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 t... | 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>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.<... | 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 particul... | 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. H... | 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 ... |
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 ... | 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-Expans... | <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-Expans... | 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></p... | 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}`
> ... |
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 ... | 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>bas... | <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>bas... | 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? ... | 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 a... | 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... |
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"]
... | 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 ... | <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 ... | 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">Ub... | 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
ech... | 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 [[ "... |
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 t... | 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 --rec... | <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 --rec... | 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/
</... | 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 multip... | 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 dow... |
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>$MyDi... | 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... | <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... | 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 det... | 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 dir... | [**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 ... |
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 another... | <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 another... | 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 `thefoldertoexcl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.