date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,361,291,930,000 |
I'm trying to format a supposedly defective hard disk using "mkfs.ext3 -cc /dev/sda1" on a partition that spans over the entire disk.
I wish to understand the meaning of the ongoing error report in mkfs.ext3's command output, on the last line: "...(109/0/0 errors)". I didn't find information about these three values i... |
When all else fails, use the actual sources! There, we see that the fields being printed are:
fprintf(stderr,
_("Pass completed, %u bad blocks found. (%d/%d/%d errors)\n"),
bb_count, num_read_errors, num_write_errors, num_corruption_errors);
In other words, they are the number of read ... | Meaning of "mkfs.ext3 -cc" error report |
1,562,066,920,000 |
I'm trying to run badblocks on a drive with a single partition. The drive contains a FreeBSD file system on it.
I boot up using a Linux live USB drive. The drive is unmounted. The output of fdisk -l is:
Device Boot Start End Id System
/dev/sda1 * 63 976773167+ a5 FreeBSD
... |
No, this isn't an indication something is wrong with the drive. You are getting this error because badblocks is accepting /dev/sda1 as the last-block argument instead of accepting it as the device.
The syntax in your question looks correct to me. Try specifying the last-block argument after the device:
badblocks -v ... | badblocks utility keeps reporting "invalid last block" |
1,562,066,920,000 |
My external hard drive was acting strangely, so I ran badblocks, and it seemed that nearly every block was bad from the first minute I ran it. If I did badblocks -v > file, the file was over 100MB after only seconds of running it.
Then, for the hell of it, I ran badlocks on the same drive without using the 10 foot USB... |
Sounds like you have a bad cable. The drive renaming itself is indicative of the USB connection being dropped and restarted and the kernel assigning the next device name to the subsequent connection.
I'd watch dmesg for USB errors while accessing the drive. If it works with the short cable, that further reinforces... | Bad blocks only with extension cord? |
1,562,066,920,000 |
I have a failed hard drive which I need to extract data from. My dd kung fu is failing me right now. I know that the drive is failing at sector 60515007 to 60517093 (512b per sector), and multiple other locations. and I need to skip that area. How do I do it in dd? And I need to compress it on the fly (piping maybe?)... |
If you really want to do this with dd, you need to split your reads up:
dd if=/dev/sda bs=512 count=60515006 | gzip -9 > dump1.gz
will dump the first 60515006 sectors of /dev/sda to dump1.gz, compressing with gzip. Then
dd if=/dev/sda bs=512 skip=60517093 count=... | gzip -9 > dump2.gz
will skip the failed part and ... | How to image certain portions of hard drive only |
1,562,066,920,000 |
I am developing for an embedded Linux application using friendlyARM's micro2440.
It runs on a Samsung s3c2440 ARM processor and uses squashfs in its NAND flash.
Recently, some flash blocks went bad. u-Boot correctly finds them and creates a bad block table with the offsets given by the nand bad command:
Device 0 bad ... |
We've figured out that the problem is with squashfs itself. It has no support for bad block detection, as stated here:
http://elinux.org/Support_read-only_block_filesystems_on_MTD_flash
So the possible solution is to use another filesystem or use UBI to manage the bad blocks and then keep using squashfs.
| Kernel does not skip bad blocks when mounting filesystem |
1,562,066,920,000 |
The badblocks utility allows one to find bad blocks on a device, and e2fsck -c allows one to add such bad blocks to the bad block inode so that they will not be used for actual data. But for SSD, it is known that bad sectors are normally reallocated (remapped) transparently by the drive (however, only when a write occ... |
Hard drives also remap failing sectors on writes, and have done so for decades; this isn’t specific to SSDs. The main wrinkle with badblocks and SSDs compared to hard drives is the amount of wear that writing an entire drive entails (but even that’s not necessarily significant).
This remapping (which doesn’t affect ex... | SSD: `badblocks` / `e2fsck -c` vs reallocated/remapped sectors |
1,562,066,920,000 |
man badblocks says:
-n Use non-destructive read-write mode. By default only a non-
destructive read-only test is done. This option must not be
combined with the -w option, as they are mutually exclusive.
This answer says:
The non-destructive read-write test works by overwriting data, t... |
The default pattern with -n is a random pattern:
const unsigned int patterns[] = { ~0 };
(see pattern_fill for the equivalence to “random”).
In destructive mode, four patterns are used:
const unsigned int patterns[] = {0xaa, 0x55, 0xff, 0x00};
| What pattern(s) does non-destructive badblocks -n write? |
1,562,066,920,000 |
Since btrfs doesn't maintain a list of badblocks, I'm looking for a work-around at a lower layer.
(I'm mining burstcoin and don't mind losing a few blocks here and there.)
It seems that LVM doesn't maintain a badblocks list also.
There is a ingenious work-around with dmsetup: creating a table avoiding current bad bloc... |
I asked on the linux-raid mailing list if this were possible, and the answer was "no".
| Use mdadm as workaround for lack of badblocks support in btrfs |
1,562,066,920,000 |
I have a 16G pendrive that has some bad blocks:
# f3read /media/morfik/224e0447-1b26-4c3e-a691-5bf1db650d21
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097112/ 40/ 0/ 0
Validating file 2.h2w ... 2097120/ 32/ 0/ 0
Validating file 3.h2w ... 2... |
I've managed to solve this problem, but I'm still wonder if there's a better and easier solution.
Anyways, if you have bad blocks at the beginning of the device and you are unable to burn a live image, you should make two partitions:
Then you download an image and check its first partition's offset:
# parted /home/... | Is it possible to burn a live image to a damaged pendrive? |
1,562,066,920,000 |
I am facing a similar problem as this: Kernel does not recognize nand bad blocks marked by u-boot
I'm using a friendlyARM micro2440 board that contains the s3c2440 ARM processor. u-Boot has found some bad blocks and written their positions in the bad block table, but when I boot the kernel it seems to be unable to fin... |
It was found that the problem did not reside in the BBT offset as previously stated. The source of the problem was the usage of squashfs, as said in this link:
http://elinux.org/Support_read-only_block_filesystems_on_MTD_flash
The solutions would be to either use another filesystem or to use UBI to detect the bad bloc... | How to find out the bad block table offset and how to change it in u-Boot |
1,562,066,920,000 |
I have an SSD that I suspect failing silently now and then. I have run badblocks on it and it is clear that it is not bad sectors but might instead be some race condition in the electronics, in which case a retry would probably read the data correctly.
Normal magnetic disks have some ECC to correct errors by taking up... |
btrfs and zfs are engineered for data integrity.
By default, btrfs duplicates meta-data on single device configurations. I think you can duplicate data too, although I've never done it.
zfs has copies=n - which I think of as RAID1 for a single-disk. Consider that the amount of redundancy chosen will negatively impact... | ECC on a single block device |
1,562,066,920,000 |
Gentlemen,
I need some fatherly advice about e2fsck: I have a disk that has been getting cranky, and "e2fsck -ccv" was indeed showing bad blocks. However, I repartitioned the disk, and now the same command reports that the disk is in perfect health! What happened to my bad blocks? Of course the partitions are now a... |
Filesystem badblock lists are obsolete (ignoring flash filesystems, because you're talking about ext4). bad blocks are remapped by the drive. Look for errors - there should be a permanent log of these in SMART counters. If you see one or more errors / "bad blocks" / "bad sectors" you should consider the disk untrus... | e2fsck: bad blocks disapearing! |
1,562,066,920,000 |
This command:
badblocks -svn /dev/sda
What does it do? Does it just report the bad blocks? Or does it somehow handle the bad blocks so that I don't need to be worried about them?
I read the manual by man badblocks, but I don't get the -n option:
-s Show the progress of the scan by writing out rough per... |
The "non-destructive read-write mode" triggered by the -n option writes the test data to each block, just like the -w, and forces the disk either to accept the write, to reallocate a faulty block, or to return a write error.
However, its big win is that it first reads the block it's about to overwrite, and re-writes t... | What does command do: `badblocks -svn /dev/sda`? does it just report the bad blocks? |
1,562,066,920,000 |
Suppose there's a hard drive /dev/sda, and both that:
/dev/sda1 is a single ext4 partition taking up the whole disk, and it's mostly empty of data.
dumpe2fs -b /dev/sda1 outputs the badblocks list, which in this case outputs single high number b representing a bad block near the end of /dev/sda; b is fortunately ... |
GParted doesn’t take any ext2/3/4 badblocks list into account; I checked this by creating an ext4 file system with a force bad block, then moving it using GParted. Running dumpe2fs -b on the moved partition shows the bad block at the same offset.
The result is 2, so the bad block ignored by the file system no longer c... | Does gparted make good use of badblocks lists? |
1,562,066,920,000 |
I got a softbricked/hardbricked 1TB WD Passport HDD which happened when transfering a suspected 11GB PS3 game file from my mac.As for repairing, My mac cannot do anything with the HDD, so I'm trying to solve it using linux machine.
by running : sudo badblocks -v /dev/sdb > badsectors.txt
I got an unlimited number of l... |
You have the highest possible read error rate:
1 Raw_Read_Error_Rate 0x002f 001 001 051 Pre-fail Always FAILING_NOW 72289
which means there's some hardware defect somewhere.
This drive is dead.
| If dd zero does not "format" my disk what should i do? |
1,562,066,920,000 |
I'm using f3 to test hundreds of USB flash memory sticks for errors.
Here's an example output from a faulty drive. First writing test files with f3write:
Free space: 3.74 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Free space: 0.00 Byte
Average wri... |
The f3 documentation says:
When f3read reads a sector (i.e. 512 bytes, the unit of communication with the card), f3read can check if the sector was correctly written by f3write, and figure out in which file the sector should be and in which position in that file the sector should be. Thus, if a sector is well formed,... | f3read - what is the difference between corrupted, changed and overwritten sectors? |
1,562,066,920,000 |
From the manpage:
badblocks - search a device for bad blocks
but as I try to isolate between software and hardware, I might need a bit more context.
Does badblocks scan for software (filesystem) or hardware (ssd) failures?
See also Ubuntu manpage entry at: https://manpages.ubuntu.com/manpages/focal/man8/badblocks.8.h... |
The answer lies in the definition of a badblock. A working definition may be:
Bad Block is an area of storing media that is no longer reliable for the storage of data because it is completely damaged or corrupted.
It is not the best definition to use with the program badblocks, but gives a general idea of what it me... | Does `badblocks` scan for software or hardware failures? |
1,562,066,920,000 |
I am running
$ uname -a
Linux myhostname 4.14.15-041415-generic #201801231530 SMP Tue Jan 23 20:33:21 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
$ lsb_release -a
No LSB modules are available.
Distributor ID: Nitrux
Description: Nitrux 1.1.4
Release: 1.1.4
Codename: nxos
It has a single hard disk with a s... |
From the e2fsck man page (e2fsck is also linked to names fsck.ext2, fsck.ext3 and fsck.ext4):
Note that in general it is not safe to run e2fsck on mounted filesystems. The only exception is if the -n option is specified, and -c, -l, or -L options are not specified. However, even if it is safe to do so, the results pr... | Avoid damaged block in ext4 |
1,562,066,920,000 |
The tool badblocks can give a list of unreadable LBA's, including logical errors I guess.
How can I differentiate between logical (soft) bad blocks and physical (hard) bad blocks?
List logical and physical errors seperately or marked as.
Indicate type of error for any given LBA.
|
As far as the harddisk is concerned, the LBA (logical block address) is supposed to be the "physical" address of the block.
For modern harddisks this is no longer true, there is an additional level of indirection which maps bad LBAs no blocks from a spare list. There is no way to get at this list, unless you hack the ... | Differentiate bad logical and physical blocks? (list seperately) |
1,562,066,920,000 |
Recently my hard disk show some error message in SMART utility, I have taken a screenshot from error messages. That's something like : Current pending sector count error && Relocated sector count . Can someone explain me how to fix such Bad Sector and Errors ?
notice : Sometimes system hangout and syslog show "Kerne... |
The best way to fix these bad sectors and to get rid of the warnings is by backing up, replacing the hardware and restoring (if the drive is part of a RAID-5, you should just swap the drive and let the RAID software reconstruct the contents).
Although you could get rid of the problems with these sectors by remapping (... | Current pending sector count error |
1,514,163,228,000 |
Is there a simple way to reverse an array?
#!/bin/bash
array=(1 2 3 4 5 6 7)
echo "${array[@]}"
so I would get: 7 6 5 4 3 2 1
instead of: 1 2 3 4 5 6 7
|
I have answered the question as written, and this code reverses the array. (Printing the elements in reverse order without reversing the array is just a for loop counting down from the last element to zero.) This is a standard "swap first and last" algorithm.
array=(1 2 3 4 5 6 7)
min=0
max=$(( ${#array[@]} -1 ))
wh... | Bash - reverse an array |
1,514,163,228,000 |
VAR=a,b,c,d
# VAR=$(echo $VAR|tr -d '\n')
echo "[$VAR]"
readarray -td, ARR<<< "$VAR"
declare -p ARR
Result:
[a,b,c,d]
declare -a ARR=([0]="a" [1]="b" [2]="c" [3]=$'d\n')
How can I tell readarray not to add the final newline \n? What is the meaning of the latest $ symbol?
|
The implicit trailing new-line character is not added by the readarray builtin, but by the here-string (<<<) of bash, see Why does a bash here-string add a trailing newline char?. You can get rid of that by printing the string without the new-line using printf and read it over a process-substitution technique < <()
re... | How to remove new line added by readarray when using a delimiter? |
1,514,163,228,000 |
Suppose I have a graphical program named app. Usage example: app -t 'first tab' -t 'second tab' opens two 'tabs' in that program.
The question is: how can I execute the command (i.e. app) from within a bash script if the number of arguments can vary?
Consider this:
#!/bin/bash
tabs=(
'first tab'
'second tab'
)... |
Giving the arguments from an array is easy, "${array[@]}" expands to the array entries as distinct words (arguments). We just need to add the -t flags. To do that, we can loop over the first array, and build another array for the full list of arguments, adding the -t flags as we go:
#!/bin/bash
tabs=("first tab" "seco... | Run a command using arguments that come from an array |
1,514,163,228,000 |
The following script fails when run with bash 4.4.20(1)
#!/bin/bash
bar() {
local args=("y")
}
foo() {
local -r args=("x")
bar
}
foo
with error line 3: args: readonly variable but succeeds when run with bash 4.2.46(2), which makes sense after reading 24.2. Local Variables.
The following script with non-array ... |
Your script runs correctly with release 5.1 of the bash shell, but not with intermediate releases after 4.3.
The bug or bugs might have been introduced around release 4.3 or 4.4. Multiple changes touched on how read-only declarations and variables work in the development leading up to both releases.
There are at leas... | Bash 4.4 local readonly array variable scoping: bug? |
1,514,163,228,000 |
Is there a way to find the length of the array *(files names) in zsh without using a for loop to increment some variable?
I naively tried echo ${#*[@]} but it didn't work. (bash syntax are welcome as well)
|
${#*[@]} would be the length of the $* array also known as $@ or $argv, which is the array of positional parameters (in the case of a script or function, that's the arguments the script or function received). Though you'd rather use $# for that.
* alone is just a glob pattern. In list context, that's expanded to the l... | Find array length in zsh script |
1,514,163,228,000 |
The following post solution works as expected:
How to pass an array as function argument?
Therefore - from his answer:
function copyFiles() {
arr=("$@")
for i in "${arr[@]}";
do
echo "$i"
done
}
array=("one 1" "two 2" "three 3")
copyFiles "${array[@]}"
The reason of this post is what ... |
It is not possible to pass an array as argument like that. Even though it looks like you do that, it does not work as you expect it
Your shell (e.g. here: bash) will expand "${array[@]}" to the individual items before executing the function !
So, this
copyFiles "Something More" "${array[@]}"
will actually call
copyFi... | How to pass an array as function argument but with other extra parameters? |
1,514,163,228,000 |
I have a piece of code which works, something like this (note this is inside CloudFormation Template for AWS auto deployment):
EFS_SERVER_IPS_ARRAY=( $(aws efs describe-mount-targets --file-system-id ${SharedFileSystem} | jq '.MountTargets[].IpAddress' -r) )
echo "IPs in EFS_SERVER_IPS_ARRAY:"
for element in "${EFS_SE... |
aws efs describe-mount-targets --file-system-id ${SharedFileSystem} \
| jq --arg mntsrc "$MOUNT_SOURCE" '.MountTargets[].IpAddress | . + $mntsrc' -r >> /etc/hosts
or, if you prefer,
aws efs describe-mount-targets --file-system-id ${SharedFileSystem} \
| jq '.MountTargets[].IpAddress' -r | sed -e "s~\$~$MOUNT_... | How to pipe multiple results into a command? |
1,514,163,228,000 |
In reading through the source to fff to learn more about Bash programming, I saw a timeout option passed to read as an array here:
read "${read_flags[@]}" -srn 1 && key "$REPLY"
The value of read_flags is set like this:
read_flags=(-t 0.05)
(The resulting read invocation intended is therefore read -t 0.05 -srn 1).
I... |
The reason is a difference in how the read builtin function and the date command interpret their command-line arguments.
But, first things first. In both of your examples, you place - as is recommended - quotes around the dereferencing of your shell variables, be it "${read_flags[@]}" in the array case or "$read_flags... | Bash's read builtin errors on a string-based timeout option specification but not an array-based one. Why? |
1,514,163,228,000 |
I don't understand why "${ARRAY[@]}" gets expanded to multiple words, when it's quoted ("...")?
Take this example:
IFS=":" read -ra ARRAY <<< "foo:bar:baz"
for e in "${ARRAY[@]}"; do echo $e; done
foo
bar
baz
Any other variable that I expand in quotes, say "${VAR}", results in a single word:
VAR="foo bar baz"
for a i... |
Because arrays when indexed with @ and double quoted expand to a list of the elements. It's documented in man bash under "Arrays":
If the word is double-quoted, ... ${name[@]} expands each element
of name to a separate word.
This behaviour is required if you don't want each element to be subject to word splitting ... | Why is "${ARRAY[@]}" expanded into multiple words, when it's quoted? |
1,514,163,228,000 |
#!/usr/bin/bash
ARGENT=("Nous devons économiser de l'argent."
"Je dois économiser de l'argent.")
BIENETRE=("Comment vas-tu?" "Tout va bien ?")
aoarrs=("${ARGENT}" "${BIENETRE}")
select arr in "${aoarrs[@]}"; do
for el in "${arr[@]}"; do
echo "$el"
done
break
done
I want this script to print the array... |
You'll store the array names in aoarrs, and inside the select body declare a nameref to the chosen name:
ARGENT=("Nous devons économiser de l'argent."
"Je dois économiser de l'argent.")
BIENETRE=("Comment vas-tu?" "Tout va bien ?")
aoarrs=(ARGENT BIENETRE)
PS3='Which array? '
select arr in "${aoarrs[@]}"; do
[[ ... | How do I select an array to loop through from an array of arrays? |
1,514,163,228,000 |
With the following code:
#! /bin/bash
declare -a arr=("element1"
"element2" "element3"
"element4" )
echo "1"
echo "${arr[@]}"
... |
Compare the output of these three loops:
#!/bin/bash
declare -a arr=("this is" "a test" "of bash")
echo "LOOP 1"
for x in ${arr[*]}; do
echo "item: $x"
done
echo
echo "LOOP 2"
for x in "${arr[*]}"; do
echo "item: $x"
done
echo
echo "LOOP 3"
for x in "${arr[@]}"; do
echo "item: $x"
done
The above script will... | What is the difference between ${array[*]} and ${array[@]}? When use each one over the other? [duplicate] |
1,514,163,228,000 |
I have an array like this:
array=(1 2 7 6)
and would like to search for the second largest value, with the output being
secondGreatest=6
Is there any way to do this in bash?
|
printf '%s\n' "${array[@]}" | sort -n | tail -2 | head -1
Print each value of the array on it's own line, sort it, get the last 2 values, remove the last value
secondGreatest=$(printf '%s\n' "${array[@]}" | sort -n | tail -2 | head -1)
Set that value to the secondGreatest variable.
Glenn Jackman had an excellent po... | Find second largest value in array |
1,514,163,228,000 |
I have an input file, names.txt, with the 1 word per line:
apple
abble
aplle
With my bash script I am trying to achieve the following output:
apple and apple
apple and abble
apple and aplle
abble and apple
abble and abble
abble and aplle
aplle and apple
aplle and abble
aplle and aplle
Here is my... |
GNU Parallel can generate all combinations of input sources.
In your case you simply use names.txt twice:
parallel -k echo {1} and {2} :::: names.txt names.txt
Or (if you really have an array):
readarray -t seqcol < names.txt
parallel -kj 20 echo {1} and {2} ::: "${seqcol[@]}" ::: "${seqcol[@]}"
| Iterating over array elements with gnu parallel |
1,514,163,228,000 |
I have 2 arrays to prcoess in bash script simultaneously.
First array contains sort of lables.
Second array contains values, as under
LABELS=(label1 label2 label3 labe4 )
VALUES=(91 18 7 4)
What's required is:
a loop that will echo the indexed-item from LABELS array & and in front of that corresponding value for that... |
Just loop over the indices. e.g.
for (( i = 0; i < "${#LABELS[@]}"; i++ ))
do echo "${LABELS[$i]} ${VALUES[$i]}"
done
Instead of echo, you can use printf for more format control, e.g.
printf '%6s: %3d\n' "${LABELS[$i]}" "${VALUES[$i]}"
to line up labels with up to 6 letters and numbers with up to 3 digits.
| echoing value in same indexes of 2 arrays simulataneously |
1,514,163,228,000 |
I need to process some strings containing paths. How do I split such a string by / as delimiter resulting in an unknown number of path-parts and how do I, in the end, extract the resulting path-parts?
cut is obviously not the tool of choice as it needs you to know the number of parts beforehand and it also doesn't out... |
In Bash, you can use read -a and a here-string to split the string into an array:
path=/foo/bar/doo
IFS=/ read -r -a parts <<< "$path"
That would give an array with the four elements (empty), foo, bar, and doo.
That doesn't work with paths containing newlines, since read treats the newline as a separator by default. ... | How do I split a string by a delimiter resulting in an unknown number of parts and how can I collect the results in an array? |
1,514,163,228,000 |
I have an array
snapshots=(1 2 3 4)
When I run
printf "${snapshots[*]}\n"
It prints as expected
1 2 3 4
But when I run
printf "${snapshots[@]}\n"
It just prints
1
without a newline. My understanding is that accessing an array with @ is supposed to expand the array so each element is on a newline but it does not a... |
printf interprets its first argument as a format string, and prints that; any further arguments are only used as required in the format string.
With printf "${snapshots[*]}\n", the first argument is the elements of the array joined with the first character of $IFS (space by default) followed by backslash and n: "1 2 3... | Why does printing an array with @ using printf in bash only print the first element? |
1,514,163,228,000 |
Consider the following example, it seems it's working fine with the index 0:
$ a1=(1 2 3)
$ a2=(a b c)
$ for x in a1 a2; do echo "${!x}"; done
1
a
$ for x in a1 a2; do echo "${!x[0]}"; done
1
a
However with the index 1 it prints nothing:
$ for x in a1 a2; do echo "${!x[1]}"; done
Arrays just by themselves are fi... |
"${!x[1]}" is an indirect reference using the element at index 1 of the array x.
$ foo=123; bar=456; x=(foo bar); echo "${!x[1]}"
456
In current versions of Bash (4.3 and above), you can use namerefs to get what you want:
$ a=(00 11 22 33 44)
$ typeset -n y=a
$ echo "${y[3]}"
33
that is, with the nameref set up, "${... | How to access further members of an array when using bash variable indirection? |
1,514,163,228,000 |
I was trying to create a bash "multidimensional" array, I saw the ideas on using associative arrays, but I thought the simplest way to do it would be the following:
for i in 0 1 2
do
for j in 0 1 2
do
a[$i$j]="something"
done
done
It is easy to set and get values, but the jumps the indexes might ... |
Array indices in bash like in ksh (whose array design bash copied) can be any arithmetic expression.
In a[$i$j]="something", the $i and $j variables are expanded, so with i=0 j=1, that becomes a[01]="something", 01 as an arithmetic expression means octal number 1 in bash. With i=0 j=10, that would be a[010]="something... | What happens if I start a bash array with a big index? |
1,514,163,228,000 |
I have two different arrays with the same length:
s=(c d e f g a b c)
f=(1 2 3 1 2 3 4 5)
how can I mix/merge/combine this two arrays, so I would get this output:
c1 d2 e3 f1 g2 a3 b4 c5
|
Something like: building a counter from 0 to arraylength - 1, then combining these elements from the arrays. Free-hand:
#!/bin/bash
...
len=${#s[@]}
for (( idx = 0; idx < len; idx++ ));
do
echo "${s[idx]}${f[idx]}"
done
| Bash - mix/merge/combine two different arrays with same length |
1,514,163,228,000 |
I am working with a server running Ubuntu 18.01 LTS and I'm trying to automate the backup of multiple virtual machines.
I have the VM names in an array and then a for loop to shut down, backup and then restart each VM. I ran this over the weekend, came in today and all the commands seem to have run, but only for the ... |
The issue turns out to be that the VBoxHeadless command starts each VM as a foreground process, so execution of the loop does not continue to the next VM until the previous one exits.
For the restart portion of the script I had to use VBoxManage instead of VBoxHeadless to start the machines. After making that change e... | Bash array only executes first index |
1,514,163,228,000 |
I have a array:
ARRAY=(12.5 6.2)
I wish to return the maximum value in ARRAY which Output is 12.5
Anyone can share me ideas?
I have try this:
max=0
for v in ${ARRAY[@]}; do
if (( $v > $max )); then max=$v; fi;
done
echo $max
But it return me:
((: 12.5 > 0 : syntax error: invalid arithmetic operator (error token... |
printf '%s\n' "${ARRAY[@]}" |
awk '$1 > m || NR == 1 { m = $1 } END { print m }'
Since the bash shell does not do floating point arithmetics, it's easier to compare floating point numbers in another language. Here I'm using awk to find the maximum of all the elements in the ARRAY array.
The printf command will outpu... | Shell script-How to return maximum value in array? |
1,514,163,228,000 |
The following code is meant to look for subdirectories in ~/Downloads. I run it with . ./script.sh. It will find them even when the user submits an incomplete name.
#!/usr/bin/bash
echo -e "\nGive me the name of a nonexitent directory and I will look for it in ~/Downloads?\n"
read word
TOGOs=("$(find ~/Downloads -m... |
${TOGOs[@]} means to take the elements of the array, break them into separate words at whitespace (assuming the default IFS), and interpret each word as a glob pattern. It's the same as $var for a scalar variable, except that it lists all the elements in turn.
If there's an empty element in the array, the splitting st... | Why isn't the `else` arm executed in this Bash script (for loop through an array)? |
1,514,163,228,000 |
I'm trying to build a basic REPL in bash.
The script dynamically populates a list of files in a directory for the user to run.
File space:
|
|\ scripts/
|| script1.sh
|| script2.sh
|
\ shell/
| shell.bashrc
| shell.desktop
From shell.bashrc, I'm using the following command to get an array of filenames:
readarray -... |
By default, find outputs results separated by newlines. By setting -d " " in the mapfile/readarray command, you are causing (assuming none of the names contains a space character) all of the results to be concatenated into a single string - newlines and all. When you then echo ${filenames[0]} (with unquoted variable e... | Can't access elements of an array built from readarray |
1,514,163,228,000 |
I trying to run command recon-all with GNU parallel freesurfer preproc i have a bash array of list of patients to run 8 patents simultaneously:
root@4d8896dfec6c:/tmp# echo ${ids[@]}
G001 G002 G003 G004 G005 G006 G007 G008
and try to run with command:
echo ${ids[@]} | parallel --jobs 28 recon-all -s {.} -all -qcache
... |
The problem is that parallel wants the input to be separated by newlines but when you use echo it is separated by spaces. In order to print some words separated by newlines you can try one of these
echo one two three | tr ' ' '\n' # in case your input can not be controlled by you
printf '%s\n' one two three ... | gnu parallel with bash array |
1,514,163,228,000 |
Perhaps this is a stupid question but two hours on Google hasn't turned up anything on point.
Simply, does a difference exist in Bash between:
X="
a
b
c
"
and
X=(
a
b
c
)
The former conforms with the definition of a variable, the latter, the definition of an array.
An array is a multi-element variable, so is this to... |
A string of newline-delimited substrings is not the same thing as an array of strings. One is a string; the other contains strings.
The fact that your string is divided into lines by the inclusion of newline characters in the string has no particular significance to the storage of the string. The shell can not index ... | Array Declaration: Double Quotes & Parentheses |
1,514,163,228,000 |
I am trying to add an element to a bash array. I looked at this question and tried to follow its advice.
This is my code:
selected_projects=()
for project_num in ${project_numbers[@]}; do
selected_project=${projects[$project_num]}
echo "selected project: $project_num $selected_project"
$selected_projects+="$sele... |
Use
selected_projects+="$selected_project"
instead of
$selected_projects+="$selected_project
Variable assignment in bash never contains $ at the beginning of variable name.
| Why isn't $ARRAY+=$var working for me? |
1,514,163,228,000 |
we want to set variable that includes words as array
folder_mount_point_list="sdb sdc sdd sde sdf sdg"
ARRAY=( $folder_mount_point_list )
but when we want to print the first array value we get all words
echo ${ARRAY[0]}
sdb sdc sdd sde sdf sdg
expected results
echo ${ARRAY[0]}
sdb
echo ${ARRAY[1]}
sdc
how to conve... |
It seems that you have (maybe unintentionally) changed the important shell variable IFS in the script. Restoring it to its usual value or unsetting it (i.e. activating its default value) solves the problem:
IFS=$' \t\n'
or
unset IFS
| linux + how to convert variable to array |
1,514,163,228,000 |
Is there a case where mapfile has benefits over arr+=(input)?
Simple examples
mapfile array name, arr:
mkdir {1,2,3}
mapfile -t arr < <(ls)
declare -p arr
output:
declare -a arr=([0])="1" [1]="2" [2]="3")
Edit:
changed title for below; the body had y as the array name, but the title had arr as the name, which this... |
They're not the same thing at all, even after IFS=$'\n'.
In bash specifically (though that syntax was borrowed from zsh¹):
arr=( $(cmd) )
(arr+=( $(cmd) ) would be used to append elements to the array; so would be compared with keys=( -1 "${!arr[@]}" ); readarray -tO "$(( ${keys[@]: -1} + 1))" arr < <(cmd)²).
Does:
... | Creating and appending to an array, mapfile vs arr+=(input) same thing or am I missing something? |
1,514,163,228,000 |
I have a function (not created by me) that outputs a series of strings inside of quotes:
command <args>
“Foo”
“FooBar”
“Foo Bar”
“FooBar/Foo Bar”
When I try to assign it to an array (Bash; BSD/Mac), instead of 4 elements, I get 7. For example, for ${array[2]} I should get “Foo Bar”, but instead, I get ”Foo with the... |
You get 7 elements because word splitting is occuring, caused by the spaces.
Set IFS=$'\n' before adding the strings to the array then you'll get 4 elements but with double quotes.
Example:
IFS=$'\n'
arr=($(command <args>))
If you want 4 elements without quotes do this:
IFS=$'\n'
arr=($(command <args> | sed s'#"##'... | Bash: converting a string with both spaces and quotes to an array |
1,514,163,228,000 |
I'm having a bit of difficulty understanding parallel procedures. Atm I'm trying to mass wipe hard drives, so have created a script, however it won't run in parallel.
for i in "${!wipe[@]}"; do
dd if=/dev/zero of=/dev/${wipe[$i]} &
wait
The dd zeros the disks but it does this one after the other so when doing... |
The script as given shouldn't run at all, because you are missing the done on the for loop. This must be an excerpt, and you've left out important parts.
Assuming the missing done is after this snippet, the wait is inside the for loop, so you start the dd in the background and then wait for it to finish before going... | Getting an array into a parallel bash script |
1,514,163,228,000 |
For example, in the snippet below, (how) is it possible to make array2 identical to array1 while still using a str variable?
~$ { str='a "b c" d'; array1=(a "b c" d); array2=( $str )
echo "${array1[1]} ${array1[2]}"
echo "${array2[1]} ${array2[2]}"; }
b c d
"b c"
|
Running str='a "b c" d', the quotes are taken literal and have no special meaning afterwards, they are just a character like any other and do not prevent word splitting anymore.
While when assigning the array using quotes, the quotes are evaluated from your shell before the assignment to prevent word splitting:
array1... | Why can't I convert a string variable into an array when some items include spaces? |
1,514,163,228,000 |
i'm trying to generate a script that ftp some files to a server using lftp. when i run these commands in shell:
DBNAME=TESTDB
ls -t /data*/${DBNAME,,}Backup/$DBNAME.0.db21.DBPART000.`date +%Y%m%d`*
i get 2 paths:
/data4/testdbBackup/TESTDB.0.db1.DBPART000.20191007010004.001
/data5/testdbBackup/TESTDB.0.db1.DBPART... |
"${BACKUP_FILE_ARRAY=[@]}" has one too many = in it.
Also, to set the array, don't use mapfile. Just use the shell pattern:
BACKUP_FILE_ARRAY=( /data*/"${DBNAME,,}"Backup/"$DBNAME.0.db21.DBPART000.$(date +%Y%m%d)"* )
(if $CURRENTDATE is set with CURRENTDATE=$(date +%Y%m%d) somewhere at the top of the script, then us... | Array only returns one element |
1,514,163,228,000 |
I've got an array that contains duplicate items, e.g.
THE_LIST=(
"'item1' 'data1 data2'"
"'item1' 'data2 data3'"
"'item2' 'data4'"
)
Based on the above, I want to create an associative array that would assign itemN as key and dataN as value.
My code iterates over the list, and assigns key => value like this (the addi... |
If the keys and values are guaranteed to be purely alphanumerical, something like this might work:
declare -A output
make_list() {
local IFS=" "
declare -A keys # variables declared in a function are local by default
for i in "${THE_LIST[@]}"
do
i=${i//\'/} # since eve... | Merge duplicate keys in associative array BASH |
1,514,163,228,000 |
I have a long line that comes as output from a git command: a=$(git submodule foreach git status). It looks like this:
a = "Entering 'Dir1/Subdir' On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean Entering 'Dir2' HEAD detached at xxxxxx nothing to commit, working tr... |
You can use readarray bash builtin and specify the delimiter within the same command:
readarray -d 'char delimiter' array <<< $variable
For example:
readarray -d '@' array <<< ${a//Entering /@}
Finally when you print each result you might want to remove the @ (or any other character used as delimiter):
echo ${array[... | How to separate long string into a string array with IFS and read, or any other method |
1,514,163,228,000 |
I'm trying to learn more bash by updating my bash_profile so that I can quickly do some adb commands that I usually have to copy-paste. I found I was creating many similar functions that all looked like this:
function andVid() {
minInputs=0
fileName="$(filNamInc $MEDIA_DIR/Videos/aaaAndroidVideo mp4)"
origCmd="... |
Using a name reference variable in the function:
arrayParser () {
declare -n arr="$1"
printf 'Array: %s\n' "${arr[*]}"
printf 'Array element at index 3: %s\n' "${arr[3]}"
}
myarray=( alpha beta gamma "bumbling bee" )
arrayParser myarray
Inside the function, any reference to the name reference variable a... | Pass the name of an array in command line to reference the array in a function |
1,514,163,228,000 |
Can the below code be easily achieved with minimum coding.
$ cluster1=(x y)
$ cluster2=(a b)
$ cluster3=(m)
$ my=$((${cluster1[0]+1}+${cluster2[0]+1}+${cluster2[0]+1}))
$ echo $my
3
$ my=$((${cluster1[1]+1}+${cluster2[1]+1}+${cluster3[1]+1}))
-bash: 1+1+: syntax error: operand expected (error token is "+")
|
Your code is generating a syntax error for each element that is not set.
$ echo "${cluster1[0]+1}+${cluster2[0]+1}+${cluster2[0]+1}"
1+1+1
$ echo "${cluster1[1]+1}+${cluster2[1]+1}+${cluster3[1]+1}"
1+1+
It would be better to count the set elements instead of trying to calculate with a generated expression in this c... | Counting and adding if some arrays has element at some index |
1,514,163,228,000 |
I've some associative arrays in a bash script which I need to pass to a function in which I need to access the keys and values as well.
declare -A gkp=( \
["arm64"]="ARM-64-bit" \
["x86"]="Intel-32-bit" \
)
fv()
{
local entry="$1"
echo "keys: ${!gkp[@]}"
echo "vals: ${gkp[@]}"
local arr="$2[@]"
e... |
You need to make the arr variable a nameref. From man bash:
A variable can be assigned the nameref attribute using the -n option
to the declare or local builtin commands (see the descriptions of de‐
clare and local below) to create a nameref, or a reference to another
variable. This allows variables t... | Access values of associative array whose name is passed as argument inside bash function |
1,514,163,228,000 |
I am trying to multiply array values with values derived from the multiplication of a loop index using bc.
#!/bin/bash
n=10.0
bw=(1e-3 2.5e-4 1.11e-4 6.25e-5 4.0e-5 2.78e-5 2.04e-5 1.56e-5 1.29e-5 1.23e-5 1.0e-5)
for k in {1..11};do
a=$(echo "$n * $k" | bc)
echo "A is $a"
arn=${bw[k-1]}
echo "Arn is ... |
bc doesn't support the scientific format. Use something that does.
For example, Perl:
a=$(perl -e "print $n * $k" )
arn=${bw[k-1]}
b=$(perl -e "printf '%.2E', $arn * $a")
echo $a $b
Output:
10 1.00E-02
20 5.00E-03
30 3.33E-03
40 2.50E-03
50 2.00E-03
60 1.67E-03
70 1.43E-03
80 1.25E-03
90 1.16E-03
100 ... | bash array multiplication using bc |
1,514,163,228,000 |
So, Let's say i have an array arr, with two element in it:
read -a arr <<< "$@"
where i would then either use it in a function or script and input two string or element like so:
read_me() {
read -a arr <<< "$@"
}
read_me "first test"
Now i already know how to get through all the elements of an array:
for i in "${arr... |
array=( 1 2 3 a b c )
for i in "${!array[@]}"; do
j=$(( ${#array[@]} - i - 1 ))
printf '%s\t%s\n' "${array[i]}" "${array[j]}"
done
Output:
1 c
2 b
3 a
a 3
b 2
c 1
In short, there is nothing stopping you from traversing the array in any order and at the same time calculate... | How to both get the original and reverse order of an array? |
1,514,163,228,000 |
I can't append to an array when I use parallel, no issues using a for loop.
Parallel example:
append() { arr+=("$1"); }
export -f append
parallel -j 0 append ::: {1..4}
declare -p arr
Output:
-bash: declare: arr: not found
For loop:
for i in {1..4}; do arr+=("$i"); done
declare -p arr
Output:
declare -a arr=([0]=... |
Your parallel appears to be the GNU one, which is a perl script that runs commands in parallel.
It tries very hard to tell what shell it is being invoked from so that the command that you pass to it is interpreted by that shell, but to do that it runs a new invocation of that shell in separate processes.
If you run:
... | Unable to append to array using parallel |
1,327,107,993,000 |
I have been looking at a few scripts other people wrote (specifically Red Hat), and a lot of their variables are assigned using the following notation
VARIABLE1="${VARIABLE1:-some_val}"
or some expand other variables
VARIABLE2="${VARIABLE2:-`echo $VARIABLE1`}"
What is the point of using this notation instead of just d... |
This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable.
excerpt
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted.
Otherwise, the value of parameter is... | Using "${a:-b}" for variable assignment in scripts |
1,327,107,993,000 |
This question is a sequel of sorts to my earlier question. The users on this site kindly helped me determine how to write a bash for loop that iterates over string values. For example, suppose that a loop control variable fname iterates over the strings "a.txt" "b.txt" "c.txt". I would like to echo "yes!" when fnam... |
If you want to say OR use double pipe (||).
if [ "$fname" = "a.txt" ] || [ "$fname" = "c.txt" ]
(The original OP code using | was simply piping the output of the left side to the right side, in the same way any ordinary pipe works.)
After many years of comments and misunderstanding, allow me to clarify.
To do OR you... | In a bash script, using the conditional "or" in an "if" statement |
1,327,107,993,000 |
I know that shell scripts just run commands as if they were executed in at the command prompt. I'd like to be able to run shell scripts as if they were functions... That is, taking an input value or string into the script. How do I approach doing this?
|
The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The count of arguments is in the shell variable "$#".
Common wa... | How can I pass a command line argument into a shell script? |
1,327,107,993,000 |
I know this question has probably been answered before. I have seen many threads about this in various places, but the answers are usually hard to extract for me. I am looking for help with an example usage of the 'sed' command.
Say I wanted to act upon the file "hello.txt" (in same directory as prompt). Anywhere ... |
sed is the stream editor, in that you can use | (pipe) to send standard streams (STDIN and STDOUT specifically) through sed and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i parameter mentioned below.
Consider the followi... | Using 'sed' to find and replace [duplicate] |
1,327,107,993,000 |
I would like to change a file extension from *.txt to *.text. I tried using the basename command, but I'm having trouble changing more than one file.
Here's my code:
files=`ls -1 *.txt`
for x in $files
do
mv $x "`basename $files .txt`.text"
done
I'm getting this error:
basename: too many arguments Try basename ... |
Straight from Greg's Wiki:
# Rename all *.txt to *.text
for file in *.txt; do
mv -- "$file" "${file%.txt}.text"
done
*.txt is a globbing pattern, using * as a wildcard to match any string. *.txt matches all filenames ending with '.txt'.
-- marks the end of the option list. This avoids issues with filenames starti... | How do I change the extension of multiple files? |
1,327,107,993,000 |
Noone should need 10 years for asking this question, like I did. If I were just starting out with Linux, I'd want to know: When to alias, when to script and when to write a function?
Where aliases are concerned, I use aliases for very simple operations that don't take arguments.
alias houston='cd /home/username/.scrip... |
An alias should effectively not (in general) do more than change the default options of a command. It is nothing more than simple text replacement on the command name. It can't do anything with arguments but pass them to the command it actually runs. So if you simply need to add an argument at the front of a single c... | In Bash, when to alias, when to script and when to write a function? |
1,327,107,993,000 |
Take the following script:
#!/bin/sh
sed 's/(127\.0\.1\.1)\s/\1/' [some file]
If I try to run this in sh (dash here), it'll fail because of the parentheses, which need to be escaped. But I don't need to escape the backslashes themselves (between the octets, or in the \s or \1). What's the rule here? What about when I... |
There are two levels of interpretation here: the shell, and sed.
In the shell, everything between single quotes is interpreted literally, except for single quotes themselves. You can effectively have a single quote between single quotes by writing '\'' (close single quote, one literal single quote, open single quote).... | What characters do I need to escape when using sed in a sh script? |
1,327,107,993,000 |
I would like to remove all leading and trailing spaces and tabs from each line in an output.
Is there a simple tool like trim I could pipe my output into?
Example file:
test space at back
test space at front
TAB at end
TAB at front
sequence of some space in the middle
some empty lines with differing TABS an... |
awk '{$1=$1;print}'
or shorter:
awk '{$1=$1};1'
Would trim leading and trailing space or tab characters1 and also squeeze sequences of tabs and spaces into a single space.
That works because when you assign something to any one field and then try to access the whole record ($0, the thing print prints be default), a... | How do I trim leading and trailing whitespace from each line of some output? |
1,327,107,993,000 |
… or an introductory guide to robust filename handling and other string passing in shell scripts.
I wrote a shell script which works well most of the time. But it chokes on some inputs (e.g. on some file names).
I encountered a problem such as the following:
I have a file name containing a space hello world, and it w... |
Always use double quotes around variable substitutions and command substitutions: "$foo", "$(foo)"
If you use $foo unquoted, your script will choke on input or parameters (or command output, with $(foo)) containing whitespace or \[*?.
There, you can stop reading. Well, ok, here are a few more:
read — To read input li... | Why does my shell script choke on whitespace or other special characters? |
1,327,107,993,000 |
I need to find my external IP address from a shell script. At the moment I use this function:
myip () {
lwp-request -o text checkip.dyndns.org | awk '{ print $NF }'
}
But it relies on perl-libwww, perl-html-format, and perl-html-tree being installed.
What other ways can I get my external IP?
|
I'd recommend getting it directly from a DNS server.
Most of the other answers below all involve going over HTTP to a remote server. Some of them required parsing of the output, or relied on the User-Agent header to make the server respond in plain text. Those change quite frequently (go down, change their name, put u... | How can I get my external IP address in a shell script? |
1,327,107,993,000 |
While running a script, I want to create a temporary file in /tmp directory.
After execution of that script, that will be cleaned by that script.
How to do that in shell script?
|
tmpfile=$(mktemp /tmp/abc-script.XXXXXX)
: ...
rm "$tmpfile"
You can make sure that a file is deleted when the scripts exits (including kills and crashes) by opening a file descriptor to the file and deleting it. The file keeps available (for the script; not really for other processes but /proc/$PID/fd/$FD is a work-... | How create a temporary file in shell script? |
1,327,107,993,000 |
The following bash syntax verifies if param isn't empty:
[[ ! -z $param ]]
For example:
param=""
[[ ! -z $param ]] && echo "I am not zero"
No output and its fine.
But when param is empty except for one (or more) space characters, then the case is different:
param=" " # one space
[[ ! -z $param ]] && echo "... |
First, note that the -z test is explicitly for:
the length of string is zero
That is, a string containing only spaces should not be true under -z, because it has a non-zero length.
What you want is to remove the spaces from the variable using the pattern replacement parameter expansion:
[[ -z "${param// }" ]]
This ... | How can I test if a variable is empty or contains only spaces? |
1,327,107,993,000 |
I have 2 graphics cards on my laptop. One is IGP and another discrete.
I've written a shell script to to turn off the discrete graphics card.
How can I convert it to systemd script to run it at start-up?
|
There are mainly two approaches to do that:
With script
If you have to run a script, you don't convert it but rather run the script via a systemd service:
Therefore you need two files: the script and the .service file (unit configuration file).
Make sure your script is executable and the first line (the shebang) is #!... | How to write startup script for Systemd? |
1,327,107,993,000 |
I'm reading an example bash shell script:
#!/bin/bash
# This script makes a backup of my home directory.
cd /home
# This creates the archive
tar cf /var/tmp/home_franky.tar franky > /dev/null 2>&1
# First remove the old bzip2 file. Redirect errors because this generates some if the archive
# does not exist. Then... |
No, this will not prevent the script from crashing. If any errors occur in the tar process (e.g.: permission denied, no such file or directory, ...) the script will still crash.
This is because of using > /dev/null 2>&1 will redirect all your command output (both stdout and stderr) to /dev/null, meaning no outputs are... | redirecting to /dev/null |
1,327,107,993,000 |
I am aware of three methods to delete all entries from a file.
They are
>filename
touch filename1
filename < /dev/null
Of these three I abuse >filename the most as that requires the least number of keystrokes.
However, I would like to know which is the most efficient of the three (if there are any more efficient me... |
Actually, the second form touch filename doesn't delete anything from the file - it only creates an empty file if one did not exist, or updates the last-modified date of an existing file.
And the third filename < /dev/null tries to run filename with /dev/null as input.
cp /dev/null filename works.
As for efficient, th... | Most efficient method to empty the contents of a file |
1,327,107,993,000 |
My problem:
I'm writing a bash script and in it I'd like to check if a given service is running.
I know how to do this manually, with $ service [service_name] status.
But (especially since the move to systemd) that prints a whole bunch of text that's a little messy to parse. I assumed there's a command made for script... |
systemctl has an is-active subcommand for this:
systemctl is-active --quiet service
will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:
systemctl is-active --quiet service && echo Service is running
If you omit --quiet it will also output the current status to its standa... | The "proper" way to test if a service is running in a script |
1,327,107,993,000 |
If you've been following unix.stackexchange.com for a while, you
should hopefully know by now that leaving a variable
unquoted in list context (as in echo $var) in Bourne/POSIX
shells (zsh being the exception) has a very special meaning and
shouldn't be done unless you have a very good reason to.
It's discussed at len... |
Preamble
First, I'd say it's not the right way to address the problem.
It's a bit like saying "you should not murder people because
otherwise you'll go to jail".
Similarly, you don't quote your variable because otherwise
you're introducing security vulnerabilities. You quote your
variables because it is wrong not to (... | Security implications of forgetting to quote a variable in bash/POSIX shells |
1,327,107,993,000 |
Is there any easy way to pass (receive) named parameters to a shell script?
For example,
my_script -p_out '/some/path' -arg_1 '5'
And inside my_script.sh receive them as:
# I believe this notation does not work, but is there anything close to it?
p_out=$ARGUMENTS['p_out']
arg1=$ARGUMENTS['arg_1']
printf "The Argume... |
If you don't mind being limited to single-letter argument names i.e. my_script -p '/some/path' -a5, then in bash you could use the built-in getopts, e.g.
#!/bin/bash
while getopts ":a:p:" opt; do
case $opt in
a) arg_1="$OPTARG"
;;
p) p_out="$OPTARG"
;;
\?) echo "Invalid option -$OPTARG" >&2
... | Passing named arguments to shell scripts |
1,327,107,993,000 |
I would like to delete the last character of a string, I tried this little script :
#! /bin/sh
t="lkj"
t=${t:-2}
echo $t
but it prints "lkj", what I am doing wrong?
|
In a POSIX shell, the syntax ${t:-2} means something different - it expands to the value of t if t is set and non null, and otherwise to the value 2. To trim a single character by parameter expansion, the syntax you probably want is ${t%?}
Note that in ksh93, bash or zsh, ${t:(-2)} or ${t: -2} (note the space) are le... | Delete the last character of a string using string manipulation in shell script |
1,327,107,993,000 |
I have been trying to parallelize the following script, specifically each of the three FOR loop instances, using GNU Parallel but haven't been able to. The 4 commands contained within the FOR loop run in series, each loop taking around 10 minutes.
#!/bin/bash
kar='KAR5'
runList='run2 run3 run4'
mkdir normFunc
for ru... |
Why don't you just fork (aka. background) them?
foo () {
local run=$1
fsl5.0-flirt -in $kar"deformed.nii.gz" -ref normtemp.nii.gz -omat $run".norm1.mat" -bins 256 -cost corratio -searchrx -90 90 -searchry -90 90 -searchrz -90 90 -dof 12
fsl5.0-flirt -in $run".poststats.nii.gz" -ref $kar"deformed.nii.gz" -... | Parallelize a Bash FOR Loop |
1,327,107,993,000 |
I'm working on a simple bash script that should be able to run on Ubuntu and CentOS distributions (support for Debian and Fedora/RHEL would be a plus) and I need to know the name and version of the distribution the script is running (in order to trigger specific actions, for instance the creation of repositories). So ... |
To get OS and VER, the latest standard seems to be /etc/os-release.
Before that, there was lsb_release and /etc/lsb-release. Before that, you had to look for different files for each distribution.
Here's what I'd suggest
if [ -f /etc/os-release ]; then
# freedesktop.org and systemd
. /etc/os-release
OS=... | How can I get distribution name and version number in a simple shell script? |
1,327,107,993,000 |
I have came across this script:
#! /bin/bash
if (( $# < 3 )); then
echo "$0 old_string new_string file [file...]"
exit 0
else
... |
shift is a bash built-in which kind of removes arguments from the beginning of the argument list. Given that the 3 arguments provided to the script are available in $1, $2, $3, then a call to shift will make $2 the new $1.
A shift 2 will shift by two making new $1 the old $3.
For more information, see here:
http://s... | What is the purpose of using shift in shell scripts? |
1,327,107,993,000 |
Most languages have naming conventions for variables, the most common style I see in shell scripts is MY_VARIABLE=foo. Is this the convention or is it only for global variables? What about variables local to the script?
|
Environment variables or shell variables introduced by the operating system, shell startup scripts, or the shell itself, etc., are usually all in CAPITALS1.
To prevent your variables from conflicting with these variables, it is a good practice to use lower_case variable names.
1A notable exception that may be worth k... | Are there naming conventions for variables in shell scripts? |
1,327,107,993,000 |
Can I redirect output to a log file and a background process at the same time?
In other words, can I do something like this?
nohup java -jar myProgram.jar 2>&1 > output.log &
Or, is that not a legal command? Or, do I need to manually move it to the background, like this:
java -jar myProgram.jar 2>$1 > output.log
job... |
One problem with your first command is that you redirect stderr to where stdout is (if you changed the $ to a & as suggested in the comment) and then, you redirected stdout to some log file, but that does not pull along the redirected stderr. You must do it in the other order, first send stdout to where you want it to... | Can I redirect output to a log file and background a process at the same time? |
1,327,107,993,000 |
I have a script which runs rsync with a Git working directory as destination. I want the script to have different behavior depending on if the working directory is clean (no changes to commit), or not. For instance, if the output of git status is as below, I want the script to exit:
git status
Already up-to-date.
# On... |
Parsing the output of git status is a bad idea because the output is intended to be human readable, not machine-readable. There's no guarantee that the output will remain the same in future versions of Git or in differently configured environments.
UVVs comment is on the right track, but unfortunately the return code ... | Determine if Git working directory is clean from a script |
1,327,107,993,000 |
I can write
VAR=$VAR1
VAR=${VAR1}
VAR="$VAR1"
VAR="${VAR1}"
the end result to me all seems about the same. Why should I write one or the other? are any of these not portable/POSIX?
|
VAR=$VAR1 is a simplified version of VAR=${VAR1}. There are things the second can do that the first can't, for instance reference an array index (not portable) or remove a substring (POSIX-portable). See the More on variables section of the Bash Guide for Beginners and Parameter Expansion in the POSIX spec.
Using quot... | $VAR vs ${VAR} and to quote or not to quote |
1,327,107,993,000 |
I want to write logic in shell script which will retry it to run again after 15 sec upto 5 times based on "status code=FAIL" if it fails due to some issue.
|
This script uses a counter n to limit the attempts at the command to five.
If the command is successful, break ends the loop.
n=0
until [ "$n" -ge 5 ]
do
command && break # substitute your command here
n=$((n+1))
sleep 15
done
| How do I write a retry logic in script to keep retrying to run it upto 5 times? |
1,327,107,993,000 |
I tried to check if the PHONE_TYPE variable contains one of three valid values.
if [ "$PHONE_TYPE" != "NORTEL" ] || [ "$PHONE_TYPE" != "NEC" ] ||
[ "$PHONE_TYPE" != "CISCO" ]
then
echo "Phone type must be nortel,cisco or nec"
exit
fi
The above code did not work for me, so I tried this instead:
if [ "$PHONE... |
I guess you're looking for:
if [ "$PHONE_TYPE" != "NORTEL" ] && [ "$PHONE_TYPE" != "NEC" ] &&
[ "$PHONE_TYPE" != "CISCO" ]
The rules for these equivalents are called De Morgan's laws and in your case meant:
not(A || B || C) => not(A) && not(B) && not (C)
Note the change in the boolean operator or and and.
Whereas... | Using the not equal operator for string comparison |
1,327,107,993,000 |
I have Linux ( RH 5.3) machine
I need to add/calculate 10 days plus date so then I will get new date (expiration date))
for example
# date
Sun Sep 11 07:59:16 IST 2012
So I need to get
NEW_expration_DATE = Sun Sep 21 07:59:16 IST 2012
Please advice how to calculate the new expiration date ( with bash , ksh... |
You can just use the -d switch and provide a date to be calculated
date
Sun Sep 23 08:19:56 BST 2012
NEW_expration_DATE=$(date -d "+10 days")
echo $NEW_expration_DATE
Wed Oct 3 08:12:33 BST 2012
-d, --date=STRING
display time described by STRING, not ‘now’
This is quite a powerful tool as you can do ... | How do I add X days to date and get new date? |
1,327,107,993,000 |
I have multiple files that contain ascii text information in the first 5-10 lines, followed by well-tabulated matrix information. In a shell script, I want to remove these first few lines of text so that I can use the pure matrix information in another program. How can I use bash shell commands to do this?
If it's... |
As long as the file is not a symlink or hardlink, you can use sed, tail, or awk. Example below.
$ cat t.txt
12
34
56
78
90
sed
$ sed -e '1,3d' < t.txt
78
90
You can also use sed in-place without a temp file: sed -i -e 1,3d yourfile. This won't echo anything, it will just modify the file in-place. If you don't need t... | How do I delete the first n lines of an ascii file using shell commands? |
1,327,107,993,000 |
The old advice used to be to double-quote any expression involving a $VARIABLE, at least if one wanted it to be interpreted by the shell as one single item, otherwise, any spaces in the content of $VARIABLE would throw off the shell.
I understand, however, that in more recent versions of shells, double-quoting is no l... |
First, separate zsh from the rest. It's not a matter of old vs modern shells: zsh behaves differently. The zsh designers decided to make it incompatible with traditional shells (Bourne, ksh, bash), but easier to use.
Second, it is far easier to use double quotes all the time than to remember when they are needed. They... | When is double-quoting necessary? |
1,327,107,993,000 |
I have written a script that runs fine when executed locally:
./sysMole -time Aug 18 18
The arguments "-time", "Aug", "18", and "18" are successfully passed on to the script.
Now, this script is designed to be executed on a remote machine but, from a local directory on the local machine. Example:
ssh root@remoteServe... |
You were pretty close with your example. It works just fine when you use it with arguments such as these.
Sample script:
$ more ex.bash
#!/bin/bash
echo $1 $2
Example that works:
$ ssh serverA "bash -s" < ./ex.bash "hi" "bye"
hi bye
But it fails for these types of arguments:
$ ssh serverA "bash -s" < ./ex.bash "--... | How can I execute local script on remote machine and include arguments? |
1,327,107,993,000 |
How can I delete the first line of a file and keep the changes?
I tried this but it erases the whole content of the file.
$sed 1d file.txt > file.txt
|
The reason file.txt is empty after that command is the order in which the shell does things. The first thing that happens with that line is the redirection. The file "file.txt" is opened and truncated to 0 bytes. After that the sed command runs, but at the point the file is already empty.
There are a few options, mos... | Delete First line of a file |
1,327,107,993,000 |
From what I've read, putting a command in parentheses should run it in a subshell, similar to running a script. If this is true, how does it see the variable x if x isn't exported?
x=1
Running (echo $x) on the command line results in 1
Running echo $x in a script results in nothing, as expected
|
A subshell starts out as an almost identical copy of the original shell process. Under the hood, the shell calls the fork system call1, which creates a new process whose code and memory are copies2. When the subshell is created, there are very few differences between it and its parent. In particular, they have the sam... | Do parentheses really put the command in a subshell? |
1,327,107,993,000 |
I want to decode URL encoding, is there any built-in tool for doing this or could anyone provide me with a sed code that will do this?
I did search a bit through unix.stackexchange.com and on the internet but I couldn't find any command line tool for decoding url encoding.
What I want to do is simply in place edit a ... |
Found these Python one liners that do what you want:
Python2
$ alias urldecode='python -c "import sys, urllib as ul; \
print ul.unquote_plus(sys.argv[1])"'
$ alias urlencode='python -c "import sys, urllib as ul; \
print ul.quote_plus(sys.argv[1])"'
Python3
$ alias urldecode='python3 -c "import sys, urllib.pa... | Decoding URL encoding (percent encoding) |
1,327,107,993,000 |
How do you check if $* is empty? In other words, how to check if there were no arguments provided to a command?
|
To check if there were no arguments provided to the command, check value of $# variable then,
if [ $# -eq 0 ]; then
>&2 echo "No arguments provided"
exit 1
fi
If you want to use $*(not preferable) then,
if [ "$*" == "" ]; then
>&2 echo "No arguments provided"
exit 1
fi
Some explanation:
The second ap... | How to check if there are no parameters provided to a command? |
1,327,107,993,000 |
I've seen this comment many times on Unix & Linux as well as on other sites that use the phrasing "backticks have been deprecated", with respect to shells such as Bash & Zsh.
Is this statement true or false?
|
There are two different meanings of "deprecated."
be deprecated: (chiefly of a software feature) be usable but regarded as obsolete and best avoided, typically due to having been superseded.
—New Oxford American Dictionary
By this definition backticks are deprecated.
Deprecated status may also indicate the feature ... | Have backticks (i.e. `cmd`) in *sh shells been deprecated? |
1,327,107,993,000 |
I just saw this in an init script:
echo $"Stopping Apache"
What is that dollar-sign for?
My research so far:
I found this in the bash manual:
extquote
If set, $'string' and $"string" quoting is performed within ${parameter} expansions enclosed in double quotes. This option is enabled by default.
...but I'm not f... |
There are two different things going on here, both documented in the bash manual
$'
Dollar-sign single quote is a special form of quoting:
ANSI C Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
$"
D... | What does it mean to have a $"dollarsign-prefixed string" in a script? |
1,327,107,993,000 |
The Windows dir directory listing command has a line at the end showing the total amount of space taken up by the files listed. For example, dir *.exe shows all the .exe files in the current directory, their sizes, and the sum total of their sizes. I'd love to have similar functionality with my dir alias in bash, but ... |
The following function does most of what you're asking for:
dir () { ls -FaGl "${@}" | awk '{ total += $4; print }; END { print total }'; }
... but it won't give you what you're asking for from dir -R *.jpg *.tif, because that's not how ls -R works. You might want to play around with the find utility for that.
| Show sum of file sizes in directory listing |
1,327,107,993,000 |
I am having a hard time defining and running my own shell functions in zsh. I followed the instructions on the official documentation and tried with easy example first, but I failed to get it work.
I have a folder:
~/.my_zsh_functions
In this folder I have a file called functions_1 with rwx user permissions. In this... |
In zsh, the function search path ($fpath) defines a set of directories, which contain files that can be marked to be loaded automatically when the function they contain is needed for the first time.
Zsh has two modes of autoloading files: Zsh's native way and another mode that resembles ksh's autoloading. The latter i... | How to define and load your own shell function in zsh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.